开发者

Unprotected get function in multithreaded system - needs volatile?

I'm working on a multi threaded program that provides access to one side of an interprocess communication system. Having never used volatile, I'm trying to figure out its proper usage.

I understand that (the relevant part) volatile tells the compiler that the variable it's applied to might be written to outside of the sequence of instructions of this thread so it should reread the memory every time it's used.

I have looked at some tutorials on volatile, but most either have the simplest examples (such as global shared variable) o开发者_JAVA技巧r just copy each other. Then from time to time I see someone positing that volatile doesn't do what you think it does. Also, some people say that if you're not writing device drivers or some such you shouldn't use volatile ( Is 'volatile' needed in this multi-threaded C++ code?). At this point I have my brain in a knot and I don't even know if the things that I worry about are real issues. So I'm wondering if there are any example code of volatile usage in OOP that I could look at.

But in particular, my main concern is about the external usage of getter function. In my code everything that I use is properly protected, however, I do provide some getter functions for private member variables that I don't protect (similar to this question Overhead of pthread mutexes?, especially the last paragraph of the first answer, or unprotected access to member in property get) because I don't want to tie my writing thread down, especially if multiple other threads are waiting in loops using the get function.

I'm worried that if I don't set the variable accessed with the get function as volatile then if some external program is waiting on it in a loop then the compiler for that external program might not reread the variable so the outside program will stay in an infinite loop. Is this a valid concern?

A very similar question is here, but I'm not sure what the answer was for c++.


The "some people" you refer to are entirely correct. The use of volatile does guarantee that the memory location is read or written each time you do that in the code. It does not guarantee that the value is current or seen by other threads that might run on a separate core or separate CPU. For that you need a memory barrier.

When used in a device driver, to read or write external hardware, this isn't a problem as the hardware will have been mapped to non-cached memory.


In C++, volatile is not used for multithreading (at least as intended in the likes of Java 5, which provides a memory barrier or the like). In C++0x, there's atomic variables, and that comes closest to Java 5-style volatile.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜