验证中...
进程在被调用时,是由CPU自行调用的,如果同时对一个数据进行操作,那么可能会导致数据不准确,需要添加互斥锁,当一条线程完成数据的操作之后,再调用另一条线程。
Raw Copy
import threading
import time
g_num = 0
def test1(num):
global g_num
for i in range(num):
# 上锁,如果之前没有被上锁,那么,上锁成功
# 如果上锁之前已经上锁了,那么此时会堵塞在这里,直到这个锁被解开
mutex.acquire()
g_num += 1
# 解锁
mutex.release()
print(" -- in test1 num = %d --" % g_num)
def test2(num):
global g_num
for i in range(num):
mutex.acquire() #上锁
g_num += 1
mutex.release()
print(" -- in test2 num = %d --" % g_num)
#创建一个互斥锁,默认没有上锁
mutex = threading.Lock()
def main():
t1 = threading.Thread(target = test1,args = (1000000,))
t2 = threading.Thread(target = test2,args = (1000000,))
t1.start()
t2.start()
time.sleep(1) # 等待上方线程执行完毕
print(" -- in main g_num = %d --" % g_num)
if __name__ == "__main__":
main()

Comment list( 0 )

Sign in for post a comment

Help Search