多线程
线程是应用程序中工作的最小单元。
多线程是现实有两种方式:
方法一:将要执行的方法作为参数传给Thread的构造方法(和多进程类似)
t = threading.Thread(target=action, args=(i,))
方法二:从Thread继承,并重写run()
所以如果重写了run,就直接调用run的函数了,如果run没有重新,就调用target函数。
实例
import threading 方法一 def worker(n): print("start worker{0}".format(n)) 方法二 class Mythread(threading.Thread): def __init__(self,args): super(Mythread,self).__init__() self.args = args def run(self): print("start MyThread{0}".format(self.args)) if __name__ == "__main__": for i in xrange(1,6): t1 = threading.Thread(target=worker,args=(i,)) t1.start() t1.join() for x in xrange(6,11): t2 = Mythread(x) t2.start() t2.join() 输出结果: start worker1 start worker2 start worker3 start worker4 start worker5 start MyThread6 start MyThread7 start MyThread8 start MyThread9 start MyThread10
线程锁
通过threading.Lock()来创建锁,函数在执行的只有先要获得锁,左后执行完以后要释放锁:
with lock:
lock.acquire()
lock.release()
import threading import time def worker(name,lock): with lock: print("start {0}".format(name)) time.sleep(5) print("end {0}".format(name)) if __name__ == "__main__": lock = threading.Lock() t1 = threading.Thread(target=worker, args=("worker1", lock)) t2 = threading.Thread(target=worker, args=("worker2", lock)) t1.start() t2.start() print("main end.") 输出结果 start worker1 main end. end worker1 #中间间隔5秒 start worker2 end worker2