关于python3互斥锁

版权声明:如果转载,请注明 https://blog.csdn.net/weixin_44607176/article/details/88669479
import threading
from threading import Thread
from threading import Lock
import time

num = 0
 
# 两个线程都抢着上锁,如果有一方上锁以后,就会导致一直阻塞,直到这个锁被解开为止
class Thread(threading.Thread):
    def run(self):
        mutex.acquire()
        for i in range(10000):
               global num
               num += 1
        print(num)
        mutex.release()
 
def test():
       global num
       mutex.acquire()  # 等待可以上锁,通知而不是轮训,没有占用CPU
       for i in range(10000):
          num += 1
       print(num)
       mutex.release()  # 解锁
   <br>mutex = Lock()
 
if &ensp;\_\_name___ == &ensp;'\_\_main__':
    t = MyThread()
    t.start()
 
# 创建一把互斥锁,默认是没有上锁的
 
thread = Thread(target=test)
thread.start()

没有更多推荐了,返回首页