这是我看到的最方便的多线程程序编写方法,如下所示:
import threading
from time import ctime,sleep
def music(func):
for i in range(2):
print ‘I was listening to %s. %s’ %(func,ctime())
sleep(1)
def move(func):
for i in range(2):
print ‘I was at the %s! %s’ %(func,ctime())
sleep(5)
threads = []
t1 = threading.Thread(target=music,args=(‘hello’,))
threads.append(t1)
t2 = threading.Thread(target=move,args=(‘world’,))
threads.append(t2)
if __name__ == ‘__main__’:
for t in threads:
t.setDaemon(True)
t.start()
t.join()
print ‘all over %s’%ctime()
其中重要的方法是 threading.Thread()
对于每个thread , setDaemon(True), start() , 最后的t.join() 保证所有的线程都退出后,主线程退出。注意,最后的t.join()为与函数__main__中,而不是在for循环中。不然主线程就直接退出了。
以上程序参考这个博客:http://www.cnblogs.com/fnng/p/3670789.html
对于多进程的处理和多线程类似,
from multiprocessing import Process
def f(name):
print(‘hello’, name)
if __name__ == ‘__main__’:
p = Process(target=f, args=(‘bob’,))
p.start()
p.join()
本文地址: http://www.bagualu.net/wordpress/archives/3785 转载请注明