并发编程四(2) 线程同步

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()

更多学习笔记移步 https://www.cnblogs.com/kknote
原文地址:https://www.cnblogs.com/kknote/p/14898738.html