volatile 关键字的意思是什么?

cadwolf 2005-04-20 04:13:47
不太明白,请赐教~
...全文
161 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
cuij7718 2005-04-21
  • 打赏
  • 举报
回复
mark
jnzsk 2005-04-21
  • 打赏
  • 举报
回复
learning!
cadwolf 2005-04-21
  • 打赏
  • 举报
回复
http://www.javaperformancetuning.com/news/qotm030.shtml

What does volatile do?

This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:

int i1; int geti1() {return i1;}
volatile int i2; int geti2() {return i2;}
int i3; synchronized int geti3() {return i3;}
geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.

On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.

Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:


The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
(Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile
majcos 2005-04-20
  • 打赏
  • 举报
回复
看看这个,比较清楚
http://community.csdn.net/Expert/topic/3846/3846261.xml?temp=.6227838
xjffj 2005-04-20
  • 打赏
  • 举报
回复
mark
sjg1981 2005-04-20
  • 打赏
  • 举报
回复
<转>
泛型<编程>:volatile——多线程程序员最好的朋友volatile修正符及让你的编译器为你检查竞态条件(race conditions)
泛型<编程>:volatile——多线程程序员最好的朋友volatile修正符及让你的编译器为你检查竞态条件(race conditions)
Andrei Alexandrescu

我不想破坏你的情绪,但这篇专栏针对多线程编程中最可怕的问题。如果说——正如前面一篇泛型<编程>所说的——写出意外安全(exception-safe)的程序很难,但写意外安全的程序和多线程编程比起来就是小孩子的玩意。
用到多线程的程序是众所周知地难写,难验证,难调试,难维护,总的来说难以驾御。不正确的多线程程序可能会运行几年都不出问题,但在某些时间条件符合时就会导致不可预料的灾难。
不用说,一个写多线程代码的程序员需要一切能得到的帮助。这篇专栏集中讨论竞态条件——在多线程程序中普遍的问题来源——让你了解如何避免它并提供给你工具,而且会让你惊喜地看到你能够让编译器积极地帮助你处理这个问题。

只是个小小的关键字
尽管C和C++标准都明显地对线程保持沉默,它们还是对多线程做了小小的让步,这种让步表现为volatile关键字。
正如它的更为人所知的伙伴const, volatile是个类型修正符(type modifier)。。它的作用是和变量连用使变量能被不同线程访问和修改。根本上说,如果没有volatile的话,要么不可能写出多线程程序,要么编译器浪费极大的优化机会。现在来解释为什么会是这种情况。
考虑下面代码:

class Gadget
{
public:
void Wait ()
{
while (!flag_)
{
Sleep(1000); //睡眠1000毫秒
}
}
void Wakeup ()
{
flag_ = true;
}
...
private:
bool flag_;
};

上面Gadget::Wait的作用是每秒检查一次flag_成员变量,如果那个变量被其他线程设为true时返回。至少这是程序员的本来意图,但,唉,Wait函数是错误的。
如果编译器断定Sleep(1000)是对外部库的一个调用,而且这个调用不可能修改成员变量flag_。那么编译器会决定在寄存器中缓存flag_并且用那个寄存器替代较慢的内存。这对单线程代码来说是非常好的优化,但在现在这个情况下,这个优化破坏了正确性:你对某个Gadget对象调用Wait后,尽管另一个线程调用了Wakeup,Wait还会永远循环下去。这是因为对flag_的修改不会反映到缓存flag_的寄存器。这个优化实在是......过度优化了。
把变量缓存到寄存器中在大多数时候是一项非常有用的优化,浪费掉就太可惜了。C和C++给你机会来显式禁用这个优化。如果你用volatile标识一个变量,编译器就不会把那个变量缓存到积存器中——对变量的每次访问都直接通过实际内存的位置。所以要让Gadget的Wait/Wakeup正常工作只要正确修饰flag_

class Gadget
{
public:
...同上...
private:
volatile bool flag_;
};

大多数对volatile用途和用法的解释到此为止,并且建议你在多线程中对基本类型加volatile标识符。但是,用volatile你可以做更多事情,因为它是C++奇妙的类型系统的一部分。

对用户定义类型使用volatile
你不单单能够在基本类型前加volatile标识符,而且也能在用户定义类型前加。在这种情况下。volatile象const一样修改这个类型(你也能够同时对同一个类型加const和volatile)
但是不象const,volatile对基本类型和用户定义类型作用不同。就是说,不象类,基本类型加了volatile标识符后仍旧支持它们所有的操作(加,乘,赋值,等等。)。比如,你能够把一个非volatile int赋给一个volatile int,但你不能把一个非volatile对象赋给一个volatile对象。
我们来举例说明volatile怎样作用于用户定义类型。

Class Gadge
{
public:
void Foo() volatile;
void Bar();
...
private:
String name_;
Int state_;
};
...
Gadget regularGadget;
Volatile Gadget volatileGadget;

如果你认为volatile对对象不起作用,那准备好被吓一跳吧。

volatileGadget.Foo(); //成功,对volatile对象调用volatile函数没有问题
regularGadget.Foo(); //成功,对非volatile对象调用volatile函数没有问题
volatileGadget.Bar(); //失败!不能对volatile对象调用非volatile函数

把无标识类型转换为对应的volatile对象很简单。然而,你不能把volatile转回无标识。你必须用cast:

Gadget& ref = const_cast<Gadget&>(volatileGadget);
Ref.Bar(); //成功

一个有volatile标识符的类只能访问它接口的子集,一个由类的实现者来控制的子集。用户只能用const_cast来获得对类型接口的完全访问。此外,就象const,volatile会从类传递到它的成员(比如,volatileGadget.name_和volatileGadget.state_是volatile变量)

volatile,临界区(Critical Sections),和竞态条件(Race Conditions)
多线程程序里最简单的也是用得最多得同步设施是mutex,一个mutext提供Acquire和Release基本功能。一旦你在某个线程中调用Acquire,任何其他调用Acquire得线程会被堵塞。稍后当那个线程调用Release,正好会有一个先前被Acquire堵塞的线程被释放。换句话说,有了一个mutex,只有一个线程可以在Acquire调用和Release调用之间得到处理器时间。在Acquire调用和Release调用之间的执行代码本身就是一个临界区。(Windows术语有点让人迷惑,因为它把mutex本身叫做一个critical section(临界区)。尽管"mutext"实际上是一个进程范围内mutex,但把他们叫做线程mutex和进程mutx会更好些。)
mutex是用来保护数据,防范竟态条件的。根据定义,当多线程对数据处理的结果由线程如何被调度决定时,一个竟态条件产生。当二个或以上的线程竞争使用同样数据时竟态条件出现。因为线程可能在任意时间点被中断,正被处理的数据可能被破坏或被误判。结果是,对数据的修改动作或者有时候时读取动作必须用临界区仔细保护起来。在面向对象编程中,这通常意味着你在一个类里存放一个mutex作为成员变量,当你在存取类的数据时使用它。
有经验的多线程程序员在阅读上面两段时可能已经在打哈欠了,但那两段的目的是提供一个热身,因为现在我们要把多线程编程和volatile联系起来了。我们通过把C++的类型世界和线程语义世界的相交之处勾画出来来做到这一点。
* 临界区之外,任何线程可以在任意时刻被任意其他线程中断,其中不存在任何控制,,所以结果是被多个线程访问的变量为volatile。这也保持了volatile的原来意图——防止编译器不小心缓存被多个线程立刻用到的值。
* 临界区之内定义有一个mutex,只有一个线程能够访问。结果是,在一个临界区内,执行代码有单线程环境的语义。使用的变量不能是volatile——你能够去除volatile标识符。

简而言之在概念上,被多个线程共享的数据在临界区外是volatile,在临界区内是非volatile.
你通过锁一个mutex来进入临界区。你通过使用一个const_cast来去除volatile标识符。你如果把这两个操作放在一起,我们就在C++类型系统和应用程序的线程语义之间建立了一个联系。我们就能够让编译器来为我们检查竟态条件。

LockingPtr
我们需要一个工具来集中一个mutex的获取操作和一个const_cast。我们来开发LockingPtr模板类,你能够用一个volatile对象obj和一个mutex对象mtx来初始化这个模板类。在这个模板类的生存期内,一个LockingPtr保持mtx始终被占用。同时,LockingPtr对去除volatile的obj提供访问。这个访问是用聪明指针方式,通过operator->和operator*来提供。在LockingPtr内执行const_cast,这个转换语义上是有效的,因为LockingPtr在生存期内保持mutex被占用。
首先我们来定义LockingPtr用到的Mutex类的骨架:

class Mutex
{
public:
void Acquire();
void Release();
...
};

为了能使用LockingPtr,你要用你操作系统用到的数据结构和基本函数来实现Mutex。
LockingPtr用受控的变量的类型来作为模板。举例来说,如果你想管理一个Widget,你使用一个LockingPtr<Widget>,这样你可以用一个类型为volatile Widget的变量来初始化它。
LockingPtr的定义非常简单。LockingPtr实现一个相对简单的smart pointer。它目的只是把一个const_cast和一个临界区集中在一起。

Template <typename T>
Class LockingPtr {
Public:
//构造/析构函数
LockingPtr(volatile T& obj, Mutex& mtx)
: pObj_(const_cast<T*>(&obj)),
pMtx_(&mtx)
{ mtx.Lock(); }
~LockingPtr()
{ pMtx_->Unlock(); }
//模拟指针行为
T& operator*()
{ return *pObj_; }
T* operator->()
{ return pObj_; }
private:
T* pObj_;
Mutex* pMtx_;
LockingPtr(const LockingPtr&);
LockingPtr& operator=(const LockingPtr&);
};

尽管简单,LockingPtr对写出正确的多线程代码非常有帮助。你应该把被几个线程共享的对象定义为volatile而且不能对它们使用const_cast——应该始终使用LockingPtr自动对象。我们通过一个例子来说明:
假设你有两个线程共享一个vector<char>对象

class SyncBuf {
public:
void Thread1();
void Thread2();
private:
typedef vector<char> BufT;
volatile BufT buffer_;
Mutex mtx_; //控制对buffer_的访问
};

在一个线程函数中,你简单地使用一个LockingPtr<BufT>来取得对buffer_成员变量的受控访问:

void SyncBuf::Thread1() {
LockingPtr<BufT> lpBuf(buffer_, mtx_);
BufT::iterator I = lpBuf->begin();
For (; I != lpBuf->end(); ++I) {
...使用*i...
}
}

这些代码既非常容易写也非常容易懂——任何时候你需要用到buffer_,你必须创建一个LockingPtr<BufT>指向它。一旦你这样做,你就能够使用vecotr的所有接口。
dj0517 2005-04-20
  • 打赏
  • 举报
回复
up
MARS.nEIL 2005-04-20
  • 打赏
  • 举报
回复
谈谈volatile和const
http://dev.csdn.net/article/58/58203.shtm
zzm_hs 2005-04-20
  • 打赏
  • 举报
回复
我也想知道,请知道的朋友指点

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧