Reputation: 533
I have 3 threads.
thread A and thread B are just writers.
thread C is a just reader.
variable is time_t.
I need to verify there is no data corruptions. If data is from thread A or from thread B, so it is OK.
But, if the result at the variable is data that is no from thread A neither not from thread B so it is corrupted
As i thought because that time_t can be write at one assembly operation so it will be OK.
Is that right?
Thanks
Upvotes: 0
Views: 103
Reputation: 171127
If you have two potentially concurrent writes(1) to a shared location without synchronisation between them, you have Undefined Behaviour and anything can happen. So this is a bad idea.
Note that even if you can't imagine bad execution based on your knowledge of the underlying architecture, the optimiser can get in the way, because it is allowed to assume UB doesn't happen.
(1) Note that even one writer and one reader without synchronisation is exactly the same UB.
Upvotes: 6
Reputation: 23497
time_t
is an arithmetic type, which can basically be integer or floating-point. You can therefore try to define an atomic time_t
as (if C++11 is available):
using atomic_time_t = std::atomic<time_t>;
This is portable as long as time_t
is trivially copyable, which likely is due to being an arithmetic type. It will work even if not being lock-free. (Floating-point specializations for std::atomic
adds C++2a.)
Example:
using atomic_time_t = std::atomic<time_t>;
int main() {
std::cout << atomic_time_t{}.is_lock_free() << std::endl;
}
This prints out 1 with GCC 7.2 x86_64 compiled with -std=c++11
.
If you need to be 100% sure about portability, or don't have C++11, protect accesses (both reads and writes) to your time_t
variable by mutex provided by your threading library.
Upvotes: 4