c++ Multithreading - how writes to a shared variable are handled

Viewed 89

As the title suggest - in C++, how writes to a shared variable in threads are handled? Do threads work with their own copy of data? I know what is shared between threads and what is not but I could not find anything on how writes to a variable are handled in multithreading scenario.

Let me give you a little background. In Java, threads work on their own copy of data. We add synchronization to ensure that the writes of thread are visible to other threads. In short, synchronization ensures that the writes are flushed to the main memory.

Is similar construct valid for c/c++? If a thread is writing to a variable, are those writes immediately updated to the main memory or is it the OS that governs how the write to main memory will occur? Do we need to add synchronization to flush those updates?

For e.g. If two threads are incrementing a counter, and I can guarantee that the first thread will always finish first with that particular task (somehow by using delayed start of second thread, may not be able to guarantee it in practice) and there won't be any mangling of instructions between the two threads, then would I always see the affect of both the threads?

Thread 1 { i++; ... do something that takes long time}
Thread 2 { i++; ... do something that takes long time}

Thanks, RG

2 Answers

Do threads work with their own copy of data?

No, not unless the data is declared thread_local.

synchronization ensures that the writes are flushed to the main memory. Is similar construct valid for c/c++? If a thread is writing to a variable, are those writes immediately updated to the main memory

Yes, but unless you use synchronization of some sort, the changes may or may not be seen - or read incorrectly, by other threads.

Do we need to add synchronization to flush those updates?

Yes, but I'm not sure I'd use the word flush. "Synchronization" is good.

For e.g. If two threads are incrementing a counter, and I can guarantee that the first thread will always finish first ...

If you can guarantee that, you have synchronization.

would I always see the affect of both the threads?

Yes, if you have the guarantee you talk about.

C++ has no guarantees about how atomicity of reads/writes and flushes to memory work, unless you use the atomic primitives such as std::atomic. Be very careful here. Lock-free programming is extremely hard to get right.

My advice is use locks.

Related