如何定义变量,以防变量的值通过线程发生变化?

问题描述 投票:0回答:1

我有

main.py
,如下所示:

...
val1, val2 = None, None
...
thread1 = threading.Thread(func1, )               
thread1.start()
while condition:
    continue
else:
    thread1.join()

#check the values of val1 and val2 after the thread had changed them
if val1!= None and val2!= None:
    do_something()

另一方面,

func1
main.py
脚本中定义如下:

...
def func1():
    global val1, val2
    val1, val2 = process_something_and_return_values()

我的问题将像我一样定义

func1()
将保证找到
val1
val2
已更改且未分配给
None

如果不是,如何进行这种设置以通过

thread

更改变量的值

PS:使用Python 2.7

更新:Python 不具备跨模块更改变量的能力。因此我想检查代码是否正确,如果它在同一个模块中?

python
1个回答
0
投票

在 function_helpers.py 中将

val1
val2
显式定义为全局变量:

val1, val2 = None

... # etc.

然后在 main.py 中仅导入模块 function_helpers ,然后引用该模块中的变量和函数。通过这种方式,两个模块共享相同的

val1
val2
实例:

import function_helpers
...
function_helpers.val1, function_helpers.val2 = None, None
...
thread1 = threading.Thread(target=function_helpers.func1)               
thread1.start()
while condition:
    continue
else:
    thread1.join()

#check the values of val1 and val2 after the thread had changed them
if function_helpers.val1!= None and function_helpers.val2!= None:
    do_something()
© www.soinside.com 2019 - 2024. All rights reserved.