这篇文章是别人文章的一个观后小结,不是什么原创。
首先第一个例子:
import threading import time def worker(): print "worker" time.sleep(1) returnfor i in xrange(5): t = threading.Thread(target=worker) t.start()倒数第二行就是对threading模块简单的实例化一下,生成一个名为t的对象,然后调用start方法执行。非常简单
第二个例子:
import threading import time def worker(): print "test" time.sleep(1) for i in xrange(5): t = threading.Thread(target=worker) t.start() print "current has %d threads" % (threading.activeCount() - 1)activeCount方法会返回threading对象的激活线程数。
第三个例子:
import threading import time def worker(): print "test" time.sleep(2) threads = [] for i in xrange(5): t = threading.Thread(target=worker) threads.append(t) t.start() for item in threading.enumerate(): print item for item in threads: print itemenumeration方法会枚举threading对象的全部线程
第四个例子:
import threading import time def worker(): time.sleep(3) print "worker" t=threading.Thread(target=worker) t.setDaemon(True) t.start() print "haha"setDaemon方法会设置后台进程。
恩,以上是threading的几个常用方法,over~
浙公网安备 33010602011771号