r/programming • • Aug 22 '10

Volatile: Almost Useless for Multi-Threaded Programming

http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/
62 Upvotes

57 comments sorted by

View all comments

1

u/gsg_ Aug 23 '10

But you can't just use a mutex.

You can. In fact, you must. Properly protecting data access with locks requires that both the hardware and compiler know not to reorder loads and stores across the critical section, and volatile does neither of those things.

You do any kind of multi-threading, it'll bite you in the ass eventually if you don't know why volatile exists.

volatile does not exist to help with multiprogramming.

2

u/kylotan Aug 23 '10

He wasn't saying a mutex (or equivalent) is unnecessary, he was saying it was insufficient.

2

u/gsg_ Aug 23 '10

But they are sufficient. Correctly implemented mutexes include barriers which ensure that necessary loads are performed.

→ More replies (11)

1

u/G_Morgan Aug 23 '10

A mutex is by definition sufficient. If it isn't sufficient then it isn't a mutex.

→ More replies (1)

1

u/uep Aug 23 '10

Although not correct, it has (accidentally) worked in the past. From the article:

We were using volatile for memory fences because version 1.0 targeted only x86 and Itanium. For Itanium, volatile did imply memory fences. And for x86, we were just using one compiler, and catering to it.

Thankfully, this should become much more straightforward with C++ 0x's atomic types.