并发编程四(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 @ 2021-06-18 11:16  我是一言  阅读(38)  评论(0编辑  收藏  举报