[英]Python share variables between functions but not threads
我正在编写一些线程化的代码,并同时使用各种不同的功能。 我有一个称为ref
的变量,每个线程都不同。
ref
是在线程函数内的函数内定义的,因此当我使用global 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.