3 ms·
I'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 the
by exDM69 10y ago
I'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.