If I want to have some bool
flag that I want to share between threads and whose lifespan is unclear because thread1, thread2, ... could be the particular last thread to use it, how can I provide such a type?
I could obviously have a shared_ptr<bool>
with a mutex to synchronize access to it. Without the shared_ptr
, however, I would just use an atomic<bool>
because it would do the job.
Now, can I combine both of the concepts by using a shared_ptr<atomic<bool>>
?
If not, what would be the easiest way to have an undetermined-lifespan bool
to share between threads? Is it the mutex?
It might be necessary to say that I have multiple jobs in my system and for each of the jobs I would like to provide an shared abort flag. If the job is already done, some thread that would like to abort the thread should not crash when it tries to set the flag. And if the thread that likes to abort the job does not keep the flag (or shared_ptr) to it, then the thread should still be able to read the flag without crash. However, if no thread uses the bool anymore, the memory should be frees naturally.