简体   繁体   English

Python在函数之间共享变量,但不共享线程

[英]Python share variables between functions but not threads

I am writing some code that i have threaded, and am using various different functions at once. 我正在编写一些线程化的代码,并同时使用各种不同的功能。 I have a variable called ref that is different for each thread. 我有一个称为ref的变量,每个线程都不同。

ref is defined within a function within the threaded function, so when I use global ref , all the threads use the same value for ref (which I don't want). ref是在线程函数内的函数内定义的,因此当我使用global ref ,所有线程都为ref使用相同的值(我不想要)。 However when I don't use global ref , other functions can't use ref as it is not defined. 但是,当我不使用全局ref ,其他函数不能使用ref因为它没有定义。

Eg: 例如:

def threadedfunction():
    def getref():
        ref = [get some value of ref]
    getref()
    def useref():
        print(ref)
    useref()
threadedfunction()

If defining ref as global doesn't fit your needs then you don't have many other options... 如果将ref定义为global不能满足您的需求,那么您没有很多其他选择...

Edit your function's parameters and returns. 编辑函数的参数并返回。 Possible solution: 可能的解决方案:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM