Python之threading的多线程与线程同步
多线程
1 import threading 2 import time 3 4 5 def a(): 6 for i in range(5): 7 print('1') 8 time.sleep(1) 9 10 11 def b(): 12 for i in range(5): 13 print('2') 14 time.sleep(2) 15 16 17 if __name__ == '__main__': 18 # 创建列表,存放线程 19 threads = [] 20 # 创建两个线程 21 th1 = threading.Thread(target=a) 22 th2 = threading.Thread(target=b) 23 # 将两个线程存放到上面的threads列表中 24 threads.append(th1) 25 threads.append(th2) 26 # 遍历列表,启动线程 27 for t in threads: 28 t.start() 29 # 遍历列表,守护线程 30 for t in threads: 31 t.join()
运行对比
使用线程同步的运行结果: 不使用线程同步的运行结果:
线程同步
1 import threading 2 import time 3 4 5 def a(): 6 for i in range(5): 7 # 获取锁,用于线程同步 8 threadLock.acquire() 9 print('1') 10 time.sleep(1) 11 # 释放锁,开启下一个线程 12 threadLock.release() 13 14 15 def b(): 16 for i in range(5): 17 # 获取锁,用于线程同步 18 threadLock.acquire() 19 print('2') 20 time.sleep(2) 21 # 释放锁,开启下一个线程 22 threadLock.release() 23 24 25 if __name__ == '__main__': 26 # 使用lock使多线程在共享资源时不会乱 27 threadLock = threading.Lock() 28 # 创建列表,存放线程 29 threads = [] 30 # 创建两个线程 31 th1 = threading.Thread(target=a) 32 th2 = threading.Thread(target=b) 33 # 将两个线程存放到上面的threads列表中 34 threads.append(th1) 35 threads.append(th2) 36 # 遍历列表,启动线程 37 for t in threads: 38 t.start() 39 # 遍历列表,守护线程 40 for t in threads: 41 t.join()

浙公网安备 33010602011771号