并发编程四(2) 线程同步 - Semaphore-加锁

Semaphore-加锁

from threading import Thread, Semaphore
import threading
import time

def worker(s,i):
    s.acquire()
    print(threading.current_thread().name + " acquire")
    time.sleep(i*2)
    print(threading.current_thread().name + " release")
    s.release()

if __name__ == "__main__":
    # 设置限制最多3个线程同时访问共享资源
    s = Semaphore(3)
    for i in range(5):
        t = Thread(target = worker, args = (s, i * 2))
        t.start()
posted @ 2022-04-05 19:07  我是一言  阅读(19)  评论(0编辑  收藏  举报