简体   繁体   中英

global variable multiple reader one writer multithread safe?

I'm trying to write a program in C++ with one global variable is read by multiple threads and updated by one thread. In this case do I need to write any semaphore like things or can I just leave it as is since only 1 thread is actually writing to the global variable so there is no possible race conditions.

Also Im a newbie in semaphore so I need to spare myself the hassle if possible.

The program is this: writer thread: check pin constantly for high voltage, set global variable when it is high

reader threads: constantly check global variable in infinite loop and do something when it is set.

It's simple: if more than one thread can access an object at the same time without synchronization and at least one of those threads is writing to the object, the program has a data race. The behavior of a program that has a data race is undefined.

You can provide synchronization by preventing simultaneous access with a mutex, or, in many cases, by using an atomic object.

If you don't properly synchronize reads and writes you can enjoy the popular parlor game of “Guessing What This Program Might Do”. There are lots of message threads that provide rationalizations for why a data race is okay under some set of circumstances. That's fine if you don't really care whether your program actually works correctly. If you do care, synchronize.

You would need to provide more context, but in general you should guard access to this variable using some kind of synchronization primitive like std::mutex . You may relax requirements if you don't care if some thread may read incorrect value, but that all depends on your use case.

You can simplify and replace "multiple readers" from your question by "single reader", and the answer would still be: you have to guard access to the shared variable from different threads, otherwise reader thread may not "observe" the change that was made by the writer thread and essentially end up reading and using wrong value.

If it's a simple integer that you are trying to read/modify from your threads, then you may use std::atomic .

It's difficult to say without knowing what would constitute a correct program in your particular case. But it's true that you won't need to worry about corrupting the memory as long as you have only one concurrent writer.

Multiple readers will get indeterminate values without locking, though. You'll definitely want to use atomic loads (seq_cst, most likely) and stores to the value, and you might want to look into the volatile keyword to prevent storing the value in a register if that's a concern in your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM