Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-Threading on multi core architecture

When you have a situation where Thread A reads some global variable and Thread B writes to the same variable, now unless read/write is not atomic on a single core, you can do it without synchronizing, however what happens when running on a multi-core machine?

like image 272
Tony The Lion Avatar asked Nov 29 '22 05:11

Tony The Lion


2 Answers

Even on a single core, you cannot assume that an operation will be atomic. That may be the case where you're coding in assembler but, if you are coding in C++ as per your question, you do not know what it will compile down to.

You should rely on the synchronisation primitives at the level of abstraction that you're coding to. In your case, that's the threading calls for C++. whether they be pthreads, Windows threads or something else entirely.

It's the same reasoning that I gave in another answer to do with whether i++ was thread-safe. The bottom line is, you don't know since you're not coding to that level (if you're doing inline assembler and/or you understand and can control what's going on under the covers, you're no longer coding at the C++ level and you can ignore my advice).

The operating system and/or OS-type libraries know a great deal about the environment they're running in, far more so than the C++ compiler would. Use of proper syncronisation primitives will save you a great deal of angst.

like image 71
paxdiablo Avatar answered Dec 09 '22 19:12

paxdiablo


It will have the same pitfalls as with a single core but with additional latency due to the L1 cache synchronization that must take place between cores.

Note - "you can do it without synchronizing" is not always a true statement.

like image 44
Amardeep AC9MF Avatar answered Dec 09 '22 18:12

Amardeep AC9MF