python threading with global variables

2024/11/18 1:52:05

i encountered a problem when write python threading code, that i wrote some workers threading classes, they all import a global file like sharevar.py, i need a variable like regdevid to keep tracking the register device id, then when one thread change it's value, then other threads can get it fresh, but the result is that: when one thread change it's value, the others still get the default value i defined in sharevar.py file, why? anything wrong with me?

# thread a
from UserShare import RegDevID
import threading
class AddPosClass(threading.Thread):
global commands
# We need a pubic sock, list to store the request
def __init__(self, queue):threading.Thread.__init__(self)self.queue = queuedef run(self):while True:data = self.queue.get()#print dataRegDevID = data#print datasend_queue.put(data)self.queue.task_done()
# thread b
import threading
from ShareVar import send_queue, RegDevID 
"""
AddPos -- add pos info on the tail of the reply
"""
class GetPosClass(threading.Thread):global commands# We need a pubic sock, list to store the requestdef __init__(self, queue):threading.Thread.__init__(self)self.queue = queuedef run(self):while True:data = self.queue.get()#print datadata = RegDevID#print datasend_queue.put(data)self.queue.task_done()
# ShareVar.py
RegDevID = '100'

That's it, when thread a changed the RegDevID, thread b still get it's default value. Thanks advanced.

    from ShareVar import RegDevIDclass Test():def __init__(self):passdef SetVar(self):RegDevID = 999def GetVar(self):print RegDevIDif __name__ == '__main__':test = Test();test.SetVar()test.GetVar()

The ShareVar.py:

RegDevID = 100

The result:

100

why?

Answer

My guess is you are trying to access the shared variable without a lock. If you do not acquire a lock and attempt to read a shared variable in one thread, while another thread is writing to it, the value could be indeterminate.

To remedy, make sure you acquire a lock in the thread before reading or writing to it.

import threading# shared lock: define outside threading class
lock = threading.RLock()
# inside threading classes...
# write with lock
with lock: #(python 2.5+)shared_var += 1
# or read with lock
with lock:print shared_var

Read about Python threading.

Answer to your bottom problem with scoping:

In your bottom sample, you are experiencing a problem with scoping. In SetVar(), you are create a label RegDevID local to the function. In GetVar(), you are attempting to read from a label RegDevID but it is not defined. So, it looks higher in scope and finds one defined in the import. The variables need to be in the same scope if you hope to have them reference the same data.

Although scopes are determined statically, they are used dynamically.At any time during execution, thereare at least three nested scopes whosenamespaces are directly accessible:

the innermost scope, which is searched first, contains the local namesthe scopes of any enclosing functions, which are searched startingwith the nearest enclosing scope,contains non-local, but alsonon-global namesthe next-to-last scope contains the current module’s global namesthe outermost scope (searched last) is the namespace containingbuilt-in names

If a name is declared global, then allreferences and assignments go directlyto the middle scope containing themodule’s global names. Otherwise, allvariables found outside of theinnermost scope are read-only (anattempt to write to such a variablewill simply create a new localvariable in the innermost scope,leaving the identically named outervariable unchanged).

Read about scoping.

https://en.xdnf.cn/q/118731.html

Related Q&A

How to write nth value of list into csv file

i have the following list : sec_min=[37, 01, 37, 02, 37, 03, 37, 04, 37, 05,....]i want to store this list into CVS file in following format: 37,01 37,02 37,03 37,04 ... and so onthis is what i coded: …

Read R function output as columns

Im trying to come up with a way to solve this question I asked yesterday:rpy2 fails to import rgl R packageMy goal is to check if certain packages are installed inside R from within python.Following th…

How does .split() work? - Python

In the following examples, I am splitting an empty string by a space. However, in the first example I explicitly used a space and in the second example, I didnt. My understanding was that .split() and …

How to get email.Header.decode_header to work with non-ASCII characters?

Im borrowing the following code to parse email headers, and additionally to add a header further down the line. Admittedly, I dont fully understand the reason for all the scaffolding around what should…

Elif syntax error in Python

This is my code for a if/elif/else conditional for a text-based adventure game Im working on in Python. The goal of this section is to give the player options on what to do, but it says there is someth…

Convert date from dd-mm-yy to dd-mm-yyyy using python [duplicate]

This question already has answers here:How to parse string dates with 2-digit year?(6 answers)Closed 7 years ago.I have a date input date_dob which is 20-Apr-53 I tried converting this to format yyyy…

sklearn pipeline transform ValueError that Expected Value is not equal to Trained Value

Can you please help me to with the following function where I got the error of ValueError: Column ordering must be equal for fit and for transform when using the remainder keyword(The function is calle…

How to show Chinese characters in Matplotlib graphs?

I want to make a graph based on a data frame that has a column with Chinese characters. But the characters wont show on the graph, and I received this error. C:\Users\march\anaconda3\lib\site-packages\…

nginx flask aws 502 Bad Gateway

My server is running great yesterday but now it returned a 502 error, how could this happen?In my access.log shows:[24/Aug/2016:07:40:29 +0000] "GET /ad/image/414 HTTP/1.1" 502 583 "-&q…

Let discord bot interact with other bots

I have a Python script for a Discord bot and I want it to send a message to another Bot and select the prompt option and then type in a message but I cant get the interaction done. It just sends the me…