IceFire IceFire - 3 months ago 7
C++ Question

What is the easiest way to provide an undetermined-lifespan bool to share between threads?

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.

Answer

Once you have created your atomic bool:

std::shared_ptr<std::atomic<bool>> flag = std::make_shared<std::atomic<bool>>(false /*or true*/);

You should be fine to use this among threads. Reference counting and memory deallocation on std::shared_ptr are thread safe.

The other thing that might be of interest is if you want some threads to opt out of reference counting, then you can use:

std::weak_ptr<std::atomic<bool>> weak_flag = flag;

...

std::shared_ptr<std::atomic<bool>> temporary_flag = weak_flag.lock();

if (temporary_flag != nullptr)
{
   // you now have safe access to the allocated std::atomic<bool> and it cannot go out of scope while you are using it
}

// now let temporary_flag go out of scope to release your temporary reference count