[Solved] 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.

Enquirer: Pablo

||
Solution #1:

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.

Respondent: Martijn Pieters
Solution #2:

The keyword “global” is what you are looking for:

import threading

queue = []
l = threading.Lock()

def f():
    global queue
    l.acquire()
    queue.append(1)
    l.release()

def g():
    print(queue)

threads = [
    threading.Thread(target=f),
    threading.Thread(target=g)
]
for t in threads:
    t.start()
for t in threads:
    t.join()
Respondent: Oyono
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.