Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An equivalent to Java volatile in Python

Does Python have the equivalent of the Java volatile concept?

In Java there is a keyword volatile. As far as I know, when we use volatile while declaring a variable, any change to the value of that variable will be visible to all threads running at the same time.

I wanted to know if there is something similar in Python, so that when the value of a variable is changed in a function, its value will be visible to all threads running at the same time.

like image 600
Pablo Avatar asked Dec 14 '18 12:12

Pablo


People also ask

What is volatile keyword in Python?

Volatile variables in concurrency programming refer to variables whose values must be retrieved from main memory each time they are accessed.

Does Python have a final keyword?

Python indeed does not have a final type, it does have immutable types such as tuples but that is something else.

What is a Java volatile variable?

The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.

Is volatile deprecated in Java?

There are some uses of volatile that are NOT deprecated, because they are useful (e.g. in code that directly loads or stores from specified memory locations, such as in device drivers).


1 Answers

As far as I know, when we use volatile while declaring a variable, any change to the value of that variable will be visible to all threads running at the same time.

volatile is a little more nuanced than that. volatile ensures that Java stores and updates the variable value in main memory. Without volatile, the JVM is free to store the value in the CPU cache instead, which has the side effect of updates to the value being invisible to different threads running on different CPU cores (threads that are being run concurrently on the same core would see the value).

Python doesn't ever do this. Python stores all objects on a heap, in main memory. Moreover, due to how the Python interpreter loop uses locking (the GIL), only one thread at a time will be actively running Python code. There is never a chance that different threads are running a Python interpreter loop on a different CPU.

So you don't need to use volatile in Python, there is no such concept and you don't need to worry about it.

like image 159
Martijn Pieters Avatar answered Oct 05 '22 04:10

Martijn Pieters