python多线程
import datetime import threading from time import sleep # 创建一个信号量,限制最多同时运行2个线程 semaphore = threading.Semaphore(2) # 创建一个线程锁 threadLock = threading.Lock() def worker(i): with semaphore: current_datetime = datetime.datetime.now() print(f"【{current_datetime}】【{i}】Thread {threading.current_thread().name} is working\n") # 在这里获取线程锁,确保只有一个线程可以执行以下代码 with threadLock: print(f"Thread {threading.current_thread().name} has the lock\n") # 在这里添加你想要保护的临界区代码 sleep(2) # 休眠模拟临界区的操作 # 离开`with threadLock`块后,线程锁会自动释放 # 创建多个线程 threads = [] for i in range(5): thread = threading.Thread(target=worker, args=(i,)) threads.append(thread) thread.start() # 等待所有线程完成 for thread in threads: thread.join() print("All threads have finished.")
本文来自博客园,作者:OTAKU_nicole,转载请注明原文链接:https://www.cnblogs.com/nicole-zhang/p/17753921.html