开发者

How do I tell GCC that a variable will be modified by multiple threads?

How do I tell GCC that a variable will be modified by multiple threads? I am开发者_如何学运维 getting problems with compiler optimizations.


Here is rather old article in Dobbs about volatile and threads http://drdobbs.com/cpp/184403766 This one is bit c++ish but it describe how volatile may be used.

But also, there are some people (including from Intel) who says "Volatile: Almost Useless for Multi-Threaded Programming" and shows why http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/ They says that direct using of atomic operations ( "load-with-acquire and store-with-release" ) and memory barriers are the solution of multi-threaded data sharing.


To amplify nos' comment above:

volatile is a hint to the compiler that the variable may be modified externally, and so the value should not be placed in a register as an optimization; every time the variable is referenced, its value should be retrieved from its location in memory.

That's great, as far as it goes, but it does nothing to prevent race conditions involving the variable, where t1 and t2 both update a variable at the same time and you don't get the ultimate value you expect. In that case, you use a lock in order to ensure that you have exclusive access to the shared variable before you modify it.

Locks aren't without their pitfalls, though, as you can get into a deadlock situation, or have rather poor performance if you're not careful.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜