python 多线程
例一:不使用多线程
#-*-coding:utf-8-*- #compare for multi threadsafety import time def worker(): print "worker" time.sleep(1) return if __name__=="__main__": for i in xrange(5): worker()
例二:使用多线程
#-*-coding:utf-8-*- import threading import time def worker(): print "worker" time.sleep(1) return for i in xrange(5): t=threading.Thread(target=worker) t.start()
例三:返回线程和主线程
#-*-coding:utf-8-*- import threading import time def worker(): print "worker" time.sleep(1) return for i in xrange(5): t=threading.Thread(target=worker) t.start() print "current has %d threads" % (threading.activeCount() - 1)
例四:threading.enumerate()的使用。此方法返回当前运行中的Thread对象列表
#!/usr/bin/python #test the variable threading.enumerate() 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 print for item in threads: print item
例五:threading.setDaemon()的使用。设置后台进程。