Read a variable in another thread
I am using linux and I have two variables that are read / written to another thread. From time to time (100ms) ThreadB reads the state of the variables and does something. It's basically while(1){ dosomething(); usleep(); }
. I am worried that variables will be cached and never updated.
What's the best way to ensure that the loop works after optimization? I think I volatile
should be doing the job, but I hear it doesn't work. Both loops fail frequently (10ms +). What's the easiest and easiest way to access them? I am using C ++ 11
I am a little unsure how to use std::atomic<int>
. Can I just use it like a regular int variable and it works as expected?
You can simply declare it as std::atomic<int>
and everything should work the way you want.
volatile
is to preserve the sequence of addresses and values ββthat the generated code must be present in the processor for reading / writing. This does not at all limit what the hardware does in order to achieve memory consistency , which is a concern atomic
. Here's an article from Intel explaining the difference.
The C and C ++ standards (since 2011) define a memory model that describes what operations are defined or undefined according to the language, and what values ββan expression produces if the program as a whole is well defined.
By standards, any program doing unsynchronized access by multiple threads to a single object (like your shared one int
), in which at least one access is write, is undefined. Declaring a variable volatile
does not make access to it synchronized. Access to variables declared as atomic
is always synchronized by definition.
In the default case, if you just use atomic<int>
it without changing anything about how you use it, you end up with so-called sequentially consistent calls, which are the most consistent across threads and therefore potentially the most costly. For your use case, this doesn't seem to be a concern - the cost is on the order of nanoseconds to microseconds, and you're polling in milliseconds. If you still need to optimize, you can specify less restrictive calls.
source to share