Python是否具有Java volatile概念的等价物?
在Java中有一个关键字volatile.据我所知,当我们volatile在声明变量时使用时,对该变量值的任何更改都将对同时运行的所有线程可见.
我想知道是否有在Python类似的东西,所以,当一个变量的值的功能被改变,其价值将是可见的在同一时间运行的所有线程.
我读过一篇关于 Python 中多线程的文章,其中他们尝试使用同步来解决竞争条件问题。我运行了下面的示例代码来重现竞争条件问题:
import threading
# global variable x
x = 0
def increment():
"""
function to increment global variable x
"""
global x
x += 1
def thread_task():
"""
task for thread
calls increment function 100000 times.
"""
for _ in range(100000):
increment()
def main_task():
global x
# setting global variable x as 0
x = 0
# creating threads
t1 = threading.Thread(target=thread_task)
t2 = threading.Thread(target=thread_task)
# start threads
t1.start()
t2.start()
# wait until threads finish their …Run Code Online (Sandbox Code Playgroud)