import threading

# lock = threading.RLock()

# RLock 递归锁
lock = threading.RLock()  
Counter = [0]


def add(C):
    lock.acquire()
    C[0] = C[0] + 1
    lock.release()


if __name__ == '__main__':
    count = 0
    threads = []
    for i in range(10):
        t = threading.Thread(target=add, args=[Counter])
        threads.append(t)

    for t in threads:
        t.start()
        t.join()

    print(Counter)
import threading

lock = threading.Condition()

Counter = [0]


def add(C):
    lock.acquire()
    lock.wait()  

    C[0] = C[0] + 1
    print(C[0])
    lock.release()


if __name__ == '__main__':
    threads = []
    for i in range(10):
        t = threading.Thread(target=add, args=[Counter])
        threads.append(t)

    for t in threads:
        t.start()

    while True:
        inp = int(input("\n>>>"))
        lock.acquire()
        lock.notify(inp)
        lock.release()
import threading

lock = threading.Event()

Counter = [0]


def add(C):
    lock.wait()

    C[0] = C[0] + 1
    print(C[0])


if __name__ == '__main__':
    threads = []
    for i in range(10):
        t = threading.Thread(target=add, args=[Counter])
        threads.append(t)

    for t in threads:
        t.start()

    inp = int(input("\n>>>"))
    # 解锁
    lock.set()

    # 加锁
    lock.clear()
    inp = int(input("\n>>>"))
    # 解锁
    lock.set()

    threads = []
    for i in range(10):
        t = threading.Thread(target=add, args=[Counter])
        threads.append(t)

    for t in threads:
        t.start()

相关文章:

  • 2021-09-07
  • 2021-05-07
  • 2021-09-28
  • 2023-04-09
  • 2021-08-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-03
  • 2020-04-11
  • 2022-01-19
  • 2022-12-23
  • 2018-09-13
  • 2021-12-15
相关资源
相似解决方案