Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ if one thread writes toggles a bool once done, is it safe to read that bool in a loop in a single other thread?

I am building a very simple program as an exercise.

The idea is to compute the total size of a directory by recursively iterating over all its contents, and summing the sizes of all files contained in the directory (and its subdirectories).

To show to a user that the program is still working, this computation is performed on another thread, while the main thread prints a dot . once every second.

Now the main thread of course needs to know when it should stop printing dots and can look up a result. It is possible to use e.g. a std::atomic<bool> done(false); and pass this to the thread that will perform the computation, which will set it to true once it is finished. But I am wondering if in this simple case (one thread writes once completed, one thread reads periodically until nonzero) it is necessary to use atomic data types for this. Obviously if multiple threads might write to it, it needs to be protected. But in this case, there's only one writing thread and one reading thread.

Is it necessary to use an atomic data type here, or is it overkill and could a normal data type be used instead?

like image 804
Qqwy Avatar asked Mar 10 '23 09:03

Qqwy


1 Answers

Yes, it's necessary.

The issue is that the different cores of the processor can have different views of the "same" data, notably data that's been cached within the CPU. The atomic part ensures that these caches are properly flushed so that you can safely do what you are trying to do.

Otherwise, it's quite possible that the other thread will never actually see the flag change from the first thread.

like image 134
Will Hartung Avatar answered Mar 13 '23 01:03

Will Hartung