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.")

 

posted @ 2023-10-10 10:13  OTAKU_nicole  阅读(4)  评论(0编辑  收藏  举报