多线程(1)
1 # 2 # 多线程 3 4 # Python中提供了threading模块来对多线程的操作, 5 # 6 # 1. 多线程实例 7 # 线程是应用程序中工作的最小单元。 8 # 9 # 多线程是现实有两种方式: 10 # 方法一:将要执行的方法作为参数传给Thread的构造方法(和多进程类似) 11 # t = threading.Thread(target=action, args=(i,)) 12 # 13 # 14 # 方法二:从Thread继承,并重写run() 15 # 看源码: 16 # P = threading.Thread 17 # p.start() _start_new_thread(self.__bootstrap, ()) self.__bootstrap_inner() 18 # self.run() 19 # try: 20 # if self.__target: 21 # self.__target(*self.__args, **self.__kwargs) 22 # 所以如果重写了run,就直接调用run的函数了,如果run没有重新,就调用target函数。 23 24 # 25 # 2. 线程锁 26 # 通过threading.Lock()来创建锁,函数在执行的只有先要获得锁,左后执行完以后要释放锁: 27 # with lock: 28 # lock.acquire() 29 # lock.release() 30 31 32 import threading 33 import time 34 def worker(name, lock): 35 with lock: 36 print("start {0}".format(name)) 37 38 time.sleep(5) 39 print("end {0}".format(name)) 40 if __name__ == "__main__": 41 42 43 lock = threading.Lock() 44 t1 = threading.Thread(target=worker, args=("worker1", lock)) 45 t2 = threading.Thread(target=worker, args=("worker2", lock)) 46 47 t1.start() 48 t2.start()