import time,threading
balance = 0
lock = threading.Lock()
def change_it(n):
    global balance
    balance = balance + n
    balance = balance - n
def run_thread(n):
    for i in range(1000000):
        #先获取锁
        lock.acquire()
        try:
            change_it(n)
        finally:
            #改完了一定要释放锁
            lock.release()

t1 = threading.Thread(target=run_thread,args=(5,))
t2 = threading.Thread(target=run_thread,args=(8,))

t1.start()
t2.start()
t1.join()
t2.join()
print(balance)

线程锁的简单实现。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-24
  • 2022-12-23
  • 2021-09-11
  • 2021-10-06
  • 2021-06-14
猜你喜欢
  • 2022-12-23
  • 2021-09-09
  • 2022-12-23
  • 2022-01-03
  • 2022-01-19
  • 2022-03-01
  • 2021-05-21
相关资源
相似解决方案