3 ms·
volatile is usually neither necessary nor sufficient for concurrency as it doesn't have correct semantics. In some simple notification cases (just a polled exit
by gpderetta 10y ago
volatile is usually neither necessary nor sufficient for concurrency as it doesn't have correct semantics. In some simple notification cases (just a polled exit flag for example), given a few assumptions about the compiler and machine model, volatile might have worked. But C11 has _Atomic and there is no excuse for volatile.
In the specific example given in the article, not only volatile, but even _Atomic would be completely superfluous. 'running' it is set once in main before any threads is spawned so there is no concurrency issues; after that every read and write access is done under the protection of the 'lock' mutex, so there is no need for any special qualification in POSIX or C11.
Interestingly, a 'volatile sig_atomic_t' used in a signal handler is both required and sufficient to communicate with the thread of execution interrupted by a signal handler and is the only portable use of the keyword.
edit: there is another portable use in conjunction with {sig,}{set,long}jmp of course.
- exDM69 10y agoI'm pretty sure the example code is not correct, but may work out of luck. The first 'running = 1' is not guaranteed to be visible to other threads because there is no synchronization around it. In practice the pthread_create will probably "fix" the race condition. My best understanding is that you need a mutex or an atomic every time you access shared data to guarantee visibility. Most CPU architectures don't need the implicit memory barriers from mutex or atomic but it's not wise to rely on it.
- gpderetta 10y agothe creation of the thread (i.e. the call to pthread_create) in main "synchronizes with" the invocation of 'worker' in the child thread; the store is sequenced before pthread_create; in turn the invocation of 'worker' is sequenced before the load in 'worker', which implies that the store 'happens before' the load, guaranteeing visibility and absence of races. This is formally guaranteed by C++11 and C11 for std::thread and thrd_create, and also by posix for pthread_create although the language is more informal. edit: missing step
- exDM69 10y agoThanks for clarification. I didn't know that creating a thread guarantees visibility like that. But it makes sense, it would be more difficult to write correct code without it.