提供不确定的寿命bool以在线程之间共享的最简单方法是什么?

时间:2016-08-23 09:47:49

标签: c++ multithreading synchronization shared-ptr atomic

如果我想要在线程之间共享一些bool标志,并且其生命周期不清楚,因为thread1,thread2,...可能是使用它的特定最后一个线程,我怎么能提供这样的一个类型?

我显然可以使用带有互斥锁的shared_ptr<bool>来同步对它的访问。但是,如果没有shared_ptr,我只会使用atomic<bool>,因为它可以完成这项工作。

现在,我可以使用shared_ptr<atomic<bool>>

组合这两个概念

如果没有,那么在线程之间分配不确定的生命周期bool最简单的方法是什么?它是互斥体吗?

可能有必要说我的系统中有多个作业,而且我希望提供一个共享中止标志的每个作业。如果作业已经完成,那么想要中止线程的某个线程在尝试设置标志时不应该崩溃。如果喜欢中止作业的线程没有保留标志(或shared_ptr),那么线程应该仍然能够在不崩溃的情况下读取标志。但是,如果没有线程再使用bool,则内存应该自然释放。

1 个答案:

答案 0 :(得分:1)

一旦你创建了原子布尔:

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

你可以在线程中使用它。 std::shared_ptr上的引用计数和内存释放是线程安全的。

另一件可能感兴趣的事情是,如果您希望某些线程选择退出引用计数,那么您可以使用:

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
相关问题