簡單的python執行緒池實現執行緒安全demo
阿新 • • 發佈:2022-05-10
from concurrent.futures import ThreadPoolExecutor import threading import time import sys sys.path.append(sys.path) test_list = [t for t in range(0,100)] # 定義一個準備作為執行緒任務的函式 index = 0 lock = threading.Lock() def action(thread_id): global index global test_list global lock while index<len(test_list):print(f'{thread_id}執行了!') try: # time.sleep(random.random()) #time.sleep(random.randint(0, 3)) lock.acquire() if index+1<len(test_list): index += 1 callback(index) else: print(f'{thread_id}任務完成了!') return except BaseException as e: print(e) finally: lock.release() def callback(index): print(test_list[index]) def start(): # 建立一個包含4條執行緒的執行緒池 with ThreadPoolExecutor(max_workers=4) as pool: # 使用執行緒執行map計算 # 後面元組有3個元素,因此程式啟動3條執行緒來執行action函式results = pool.map(action,(1,2,3,4)) print('--------------') if __name__ == '__main__': pass