LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Multithreaded reading and writing of a shared integer (https://www.linuxquestions.org/questions/programming-9/multithreaded-reading-and-writing-of-a-shared-integer-842449/)

wtruong 11-04-2010 07:35 PM

Multithreaded reading and writing of a shared integer
 
Hi guys,

It it safe to read a shared integer while another thread is writing to it on a multicore system? I guess the main question here is if the system call to write is atomic for primitives.

neonsignal 11-04-2010 11:40 PM

The reading and writing of integers is not a system call, so it is not explicitly protected in any way.

It will mostly work, but there are circumstances in which it is unsafe. For example, the integer type might be larger than the size of the write, or it might not be on a word boundary, and so on. You would also have to watch out for caching and reordering and so on affecting the logic of your code.

You would want to have a good reason for doing this sort of trick.

paulsm4 11-05-2010 01:10 AM

Hi -

Let's make it simpler:

No: reading and writing a global variable shared between multiple threads is not safe. Not under any circumstances, but especially not under a multi-core CPU.

syg00 11-05-2010 01:22 AM

... unless the app manages locking (properly).


All times are GMT -5. The time now is 06:02 PM.