Crossin的编程教室
标题:
关于 多线程全局变量共享(上互斥锁)的基础问题
[打印本页]
作者:
luiz
时间:
2019-4-30 15:50
标题:
关于 多线程全局变量共享(上互斥锁)的基础问题
我真佛了,自己码的代码跟某培训视频一模一样,但为啥我这里上了互斥锁就实现不了 全局变量共享了呢?
代码如下:
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----
结果的意思是说,同一时间只能有一个进程调用全局变量 进行计算?
作者:
luiz
时间:
2019-4-30 16:11
已解决,语法小毛病
欢迎光临 Crossin的编程教室 (https://bbs.crossincode.com/)
Powered by Discuz! X2.5