0

我需要检查我创建的 boost::thread 是否从另一个线程运行。这个SO post 解释了你可以通过调用来做到这一点:

boost::posix_time::seconds waitTime(0);
myBoostThread.timed_join(waitTime);

我的客户端线程中不能有任何关键部分。我可以保证timed_join()使用 0 时间参数是无锁的吗?

4

2 回答 2

1

不,没有这样的保证。
即使 boost 实现是完全无锁的(我没有检查过),也不能保证底层操作系统实现是完全无锁的。

也就是说,如果在这里使用锁,我会发现它们不太可能导致应用程序出现任何重大延迟,所以我会毫不犹豫地使用timed_join,除非有一个硬的实时截止日期要满足(这不等同于 UI 响应能力) )。

于 2013-01-25T13:09:05.477 回答
1

Boost.Thread 不保证无锁timed_join()。但是,总是会发生变化的实现:

  • Boost.Thread 为 pthread 获取互斥锁,然后对条件变量执行定时等待。
  • Boost.Thread 调用WaitForMultipleObjects窗口。它的文档表明它总是会立即返回。但是,我不知道底层操作系统实现是否是无锁的。

作为替代方案,请考虑使用原子操作。虽然 Boost 1.52 当前不提供公共原子库,但 Boost.Smart_Ptr 和 Boost.Interprocess 在其详细命名空间中都有原子整数。但是,这些都不能保证无锁实现,并且 Boost.Smart_Ptr 的配置之一将使用pthread mutex. 因此,您可能需要查阅编译器和系统文档来确定无锁实现。

不过,这里有一个小例子,使用boost::detail::atomic_count

#include <boost/chrono.pp>
#include <boost/detail/atomic_count.hpp>
#include <boost/thread.hpp>

// Use RAII to perform cleanup.
struct count_guard
{
  count_guard(boost::detail::atomic_count& count) : count_(count) {}
  ~count_guard() { --count_; }
  boost::detail::atomic_count& count_;
};

void thread_main(boost::detail::atomic_count& count)
{
  // Place the guard on the stack. When the thread exits through either normal
  // means or the stack unwinding from an exception, the atomic count will be
  // decremented.
  count_guard decrement_on_exit(count);
  boost::this_thread::sleep_for(boost::chrono::seconds(5));
}

int main()
{
  boost::detail::atomic_count count(1);
  boost::thread t(thread_main, boost::ref(count));

  // Check the count to determine if the thread has exited.
  while (0 != count)
  {
    std::cout << "Sleeping for 2 seconds." << std::endl;
    boost::this_thread::sleep_for(boost::chrono::seconds(2));
  }
}

在这种情况下,at_thread_exit()扩展可以用作使用RAII的替代方法。

于 2013-01-25T16:49:09.597 回答