本文的python版本:3.3.3
python的多线程代码网上到处都是,但是基于python3的不太好找,这里作者备份下最简单的3种实例。
python3的lib:
【 https://docs.python.org/3.3/library/threading.html#module-threading 】
【 https://docs.python.org/3.3/library/_thread.html#module-_thread 】
CONTENTS
最简单的多线程
基于_thread
import _thread import time def hello(index, count): while count > 0: count = count - 1; time.sleep(1); print("hello from %d, count = %d"%(index, count)); if __name__=='__main__': _thread.start_new_thread(hello,(1,5)); _thread.start_new_thread(hello,(2,8));
继承threading.Thread
import threading import time class Hello(threading.Thread): def __init__(self,threadname, count): print("Hello Thread Init"); threading.Thread.__init__(self,name = threadname) self.count = count; def run(self): while self.count > 0: self.count = self.count -1; time.sleep(1); print("hello from %s, count = %d"%(self.name, self.count)); if __name__=='__main__': thread1 = Hello("A", 5); thread2 = Hello("B", 8); thread1.start(); thread2.start();
使用threading.Thread构造函数
import threading import time def hello(index, count): while count > 0: count = count - 1; time.sleep(1); print("hello from %d, count = %d"%(index, count)); if __name__=='__main__': thread1 = threading.Thread(target=hello,args=(1, 5)); thread2 = threading.Thread(target=hello,args=(2, 8)); thread1.start(); thread2.start();
多线程同步及队列
暂时先略过。。
发表评论