等效于Python中的Java volatile [英] An equivalent to Java volatile in Python

查看:93
本文介绍了等效于Python中的Java volatile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python等同于Java volatile 概念吗?

Does Python have the equivalent of the Java volatile concept?

在Java中,有一个关键字 volatile .据我所知,当我们在声明变量时使用 volatile 时,对该变量值的任何更改将对同时运行的所有线程可见.

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.

我想知道Python中是否有类似的东西,以便在函数中更改变量的值时,它的值对同时运行的所有线程可见.

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.

推荐答案

据我所知,当我们在声明变量时使用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.

volatile 的细微之处要多于此. volatile 可确保Java在主存储器中存储和更新变量值 .如果没有 volatile ,JVM可以自由地将值存储在CPU缓存中,这对值的更新具有副作用,该更新对于在不同CPU上运行的不同线程不可见内核(在同一内核上同时运行的线程将看到该值).

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从来没有这样做.Python将所有对象存储在主内存中的堆中.此外,由于Python解释程序循环如何使用锁定(GIL),因此一次仅一个线程将主动运行Python代码.永远不可能有不同的线程在不同的CPU上运行Python解释器循环.

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.

因此,您无需在Python中使用 volatile ,就没有这样的概念,也无需担心.

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

这篇关于等效于Python中的Java volatile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆