Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use global variable in python, in a threadsafe way

I want to use a global variable, Init it once. having a thread safe access.

Can someone share an example please?

like image 552
Dotan Levi Avatar asked Feb 20 '13 11:02

Dotan Levi


People also ask

How do you manipulate a global variable in Python?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword. E.g. This would change the value of the global variable to 55.

Can a thread use global variables?

Threads share all global variables; the memory space where global variables are stored is shared by all threads (though, as we will see, you have to be very careful about accessing a global variable from multiple threads).

Why are global variables not thread-safe?

Global variables are still not thread safe because there's still no protection against most race conditions. You can still have a scenario where one worker gets a value, yields, another modifies it, yields, then the first worker also modifies it.

How do I share global variables across modules Python?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Import the config module in all modules of your application; the module then becomes available as a global name.


2 Answers

If you need read-only access and the value is initialized before threads are spawn, you don't need to worry about thread safety.

If that is not the case Python threading library is probably what you need, more precisely locks. A really good read on the subject - http://effbot.org/zone/thread-synchronization.htm with quite a lot of examples.

like image 104
dmg Avatar answered Sep 19 '22 17:09

dmg


You do have a problem if you are using multiprocessing.Processes. In which case you should take a look at Managers and Queues in the multiprocessing module.

like image 22
owobeid Avatar answered Sep 17 '22 17:09

owobeid