https://www.cnblogs.com/wj-1314/p/8263328.html
threading 模块
先上代码:
1 import time, threading 2 3 def loop(): 4 print("thread %s is running..." %threading.current_thread().name) 5 n = 0 6 while n<5: 7 n += 1 8 print('thread %s >>> %s'%(threading.current_thread().name, n)) 9 time.sleep(1)10 print("thread %s ended." %threading.current_thread().name)11 12 def loop1():13 x = 114 while x <3:15 print(x,"loop1的线程")16 x += 117 time.sleep(2)18 19 if __name__ == "__main__":20 print("thread %s is running ..." %threading.current_thread().name)21 t = threading.Thread(target = loop, name = "LoopThread")22 t1 = threading.Thread(target = loop1)23 t.start()24 t1.start()25 t.join()26 t1.join()27 print("thread %s ended." % threading.current_thread().name)28 29 30 """31 thread MainThread is running ...32 thread LoopThread is running...133 thread LoopThread >>> 134 loop1的线程35 thread LoopThread >>> 236 2thread LoopThread >>> 3 37 loop1的线程38 thread LoopThread >>> 439 thread LoopThread >>> 540 thread LoopThread ended.41 thread MainThread ended.42 43 """
由于任何进程默认就会启动一个线程,我们把该线程称为主线程,主线程又可以启动新的线程,Python的threading
模块有个threading.current_thread() 获取当前线程的实例。
但是有些情况下,多线程会产生场景上的错误,比如
import time, threading# 假定这是你的银行存款:balance = 0def change_it(n): # 先存后取,结果应该为0: global balance balance = balance + n balance = balance - ndef run_thread(n): for i in range(100000): change_it(n)t1 = threading.Thread(target=run_thread, args=(5,))t2 = threading.Thread(target=run_thread, args=(8,))t1.start()t2.start()t1.join()t2.join()print(balance)
结果有时会报错
如果我们要确保balance
计算正确,就要给change_it()
上一把锁,当某个线程开始执行change_it()
时,我们说,该线程因为获得了锁,因此其他线程不能同时执行change_it()
,只能等待,直到锁被释放后,获得该锁以后才能改。由于锁只有一个,无论多少线程,同一时刻最多只有一个线程持有该锁,所以,不会造成修改的冲突。创建一个锁就是通过threading.Lock()
来实现:
import time, threadinglock = threading.Lock()# 假定这是你的银行存款:balance = 0def change_it(n): # 先存后取,结果应该为0: global balance balance = balance + n balance = balance - ndef run_thread(n): for i in range(100000): lock.acquire() try: change_it(n) finally: lock.release() t1 = threading.Thread(target=run_thread, args=(5,))t2 = threading.Thread(target=run_thread, args=(8,))t1.start()t2.start()t1.join()t2.join()print(balance)