用法:
先例項化 lock = threading.lock()
1. lock.acquire() 上鎖
需上鎖**
lock.release() 解鎖
2. with lock: 上下兩種方式都行
需上鎖**
整體**:
import threading
lock = threading.lock() 建立例項
a = 0
def func(n):
global a
for i in range(n):
lock.acquire() 上鎖
a += 1
lock.release() 解鎖
def func2(n):
global a
for i in range(n):
lock.acquire() 上鎖
a -= 1
lock.release() 解鎖
t1 = threading.thread(target = func,args = (10000,))
t1.start()
t2 = threading.thread(target = func,args = (10000,))
t2.start()
t1.join() 主程序等待
t2.join()
print(a)
圖例:
第38條 執行緒中使用Lock來防止資料競爭
python在內建的threading模組中提供了lock類,該類相當於互斥鎖,可以保護各執行緒資料結構不被破壞。案例 新建乙個counter類,統計感測器取樣獲得的樣本數量。計數器 class counter object def init self self.count 0def increme...
C 多執行緒lock解決資料同步
1.例項 public class threadtest4 public static int number 1 public static void threadmethod number thread.currentthread.managedthreadid,number thread.sle...
C 多執行緒lock解決資料同步
1.例項 public class threadtest4 public static int number 1 public static void threadmethod number thread.currentthread.managedthreadid,number thread.sle...