简体   繁体   中英

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 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). However when I don't use global ref , other functions can't use ref as it is not defined.

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...

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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