1.方式一,使用多线程
import thread,time def my(a,b): for i in range(1,20): print i if __name__=='__main__': thread.start_new_thread(my,(1,2)) thread.start_new_thread(my,(2,2))
这个是有错误的,应为main程序会直接退出,导致sys.excepthook is missing 的错误。这个错误产生的原因是:系统已经产生错误但是没有被捕捉到,其实很好理解
import thread,time def my(a,b): for i in range(1,20): print i if __name__=='__main__': thread.start_new_thread(my,(1,2)) thread.start_new_thread(my,(2,2)) time.sleep(5)
应该是线程是存在与进程中的,进程都结束了,肯定错误的了,所以给一个time.sleep(5)让主进程休息会,线程跑起来.
2.方式2
import threading,time class a(threading.Thread): def run(self): for i in range(5): print self.name def test(): for i in range(5): t=a() t.start() if __name__=='__main__': test()
使用高度封装的threading.Thread 感觉就是好用了很多,错误也少了
3.Combine with Queue
然后就是线程之间的通信了,锁什么的,不过这个我可不喜欢,我觉得容易出错,所以,参看前辈们的,使用Queue降低复杂度
import threading,time,Queue class Worker(threading.Thread): def __init__(self,queue): self.__queue=queue threading.Thread.__init__(self) def run(self): while 1: item=self.__queue.get() if item is None: break print "task",item,'\n' queue=Queue.Queue(0) for i in range(3): Worker(queue).start() for i in range(10): queue.put(i) for i in range(3): queue.put(None)
4.To be continue ( thread comunication)