函数之间但不是线程的Python共享变量
问题描述:
我写了一些代码,我有线程,并且一次使用各种不同的函数。我有一个名为ref
的变量,每个线程都有所不同。函数之间但不是线程的Python共享变量
ref
是在线程函数内的函数中定义的,所以当我使用全局线程ref
时,所有线程对于ref
(我不想要)使用相同的值。但是,当我不使用全局ref
时,其他函数不能使用ref
,因为它没有被定义。
例如为:
def threadedfunction():
def getref():
ref = [get some value of ref]
getref()
def useref():
print(ref)
useref()
threadedfunction()
答
如果定义ref
为global
不适合你的需求,那么你没有太多其他选择......
编辑你的函数的参数和返回。可能的解决方案:
def threadedfunction():
def getref():
ref = "Hello, World!"
return ref # Return the value of ref, so the rest of the world can know it
def useref(ref):
print(ref) # Print the parameter ref, whatever it is.
ref = getref() # Put in variable ref whatever function getref() returns
useref(ref) # Call function useref() with ref's value as parameter
threadedfunction()
+0
非常感谢 –
您是否听说过参数和返回值?您应该使用这些来传递数据进出功能。 – user2357112
这是你甚至在考虑做多线程任何事情之前需要100%满意的东西。 – user2357112
如果您在线程之间编写代码,则还需要使用线程安全类型。 Python的内置类型不保证是安全的。 –