此處的示例是對書籍《python並行編程》代碼的改進,文檔地址:https://python-parallel-programmning-cookbook.readthedocs.io/zh_CN/latest/chapter2/06_Thread_synchronization_with_Lock_and_Rlock.html
用threading模塊來實現並行編程
import threading
import time
import random
def function(i):
num = random.randint(1,10)
time.sleep(num)
print("sleep: %s function called by thread %i \n" % (num, i))
return
threads = []
for i in range(1, 6):
t = threading.Thread(target=function, args=(i, ))
threads.append(t)
t.start()
for t in threads:
t.join()
運行結果:
文檔中的代碼存在問題,進行了2處修復,加入sleep, 修改join函數的調用位置。加入time.sleep的原因,只有在線程sleep或者線程執行時間到達了cpu的時間片之後,線程纔會切換,如果不加time.sleep,線程的執行順序和for循環的執行順序一致