- 帖子
- 8
- 精华
- 0
- 积分
- 44
- 阅读权限
- 10
- 注册时间
- 2019-4-3
- 最后登录
- 2019-7-31
|
我真佛了,自己码的代码跟某培训视频一模一样,但为啥我这里上了互斥锁就实现不了 全局变量共享了呢?
代码如下:
import threading
import time
g_num = 0 #定义全局变量
def test1(nums):
global g_num
mutex.acquire()
for i in range(nums):
g_num += 1
mutex.release
print('----in test1 g_num = %d---' % g_num)
def test2(nums):
global g_num
mutex.acquire()
for i in range(nums):
g_num += 1
mutex.release
print('----in test2 g_num = %d---' % g_num)
mutex = threading.Lock()
def main():
t1 = threading.Thread(target=test1,args = (1000,))
t2 = threading.Thread(target=test2,args = (1000,))
t1.start()
t2.start()
time.sleep(1) # 等待上边两个线程执行完毕
print('----Thread All--g_num = %d----' % g_num)
if __name__ == '__main__':
main()
结果如下:
----in test1 g_num = 1000---
----Thread All--g_num = 1000----
结果的意思是说,同一时间只能有一个进程调用全局变量 进行计算?
|
|