C++中的std::thread类与std::this_thread命名空间有何区别?

6

既然我们已经有了 std::thread 类,为什么还需要 std::this_thread 命名空间?

它们之间的基本区别是什么?

我应该在什么情况下使用 std::thread 类以及何时使用 std::this_thread 命名空间?


4
要是能在某个地方找到文档就好了…… - juanchopanza
所以我想你已经阅读了参考文档,你应该看到它与std::thread的功能基本不同。你能更具体地说明一下,你实际上不清楚什么吗? - πάντα ῥεῖ
2个回答

5
this_thread命名空间包含访问当前线程的函数,因此当我们需要在当前线程上执行某些操作时,不需要访问该线程的thread对象。
线程类不提供让出和睡眠的访问权限,这些函数只对当前线程有意义,因此可以在this_thread命名空间中找到。
如果我们需要有关其他线程的信息,则需要该线程的thread实例,如果需要访问当前线程,则始终可以通过this_thread命名空间中的函数来完成。
使用this_thread命名空间的想法也已在扩展草案中得到解释:

this_thread Namespace

Note the use of the this_thread namespace to disambiguate when you are requesting the id for the current thread, vs the id of a child thread. The get_id name for this action remains the same in the interest of reducing the conceptual footprint of the interface. This design also applies to the cancellation_requested function:

std::thread my_child_thread(f);
typedef std::thread::id ID:

ID my_id std::this_thread::get_id();  // The current thread's id
ID your_id my_child_thread.get_id();  // The child   thread's id

bool have_i_been_canceled = std::this_thread::cancellation_requested();  // Current thread's cancellation status
bool have_you_been_canceled = my_child_thread.cancellation_requested();  // Child   thread's cancellation status
this_thread命名空间中的函数作为thread类的静态成员添加是可行的,但这样做会导致get_id函数必须被重命名,以使其与线程类中已经存在的get_id函数明显区分开来。换句话说,我猜测C++团队决定将这些函数添加到单独的命名空间中,以更清楚地表明这些函数正在读取或操作当前线程,如果它们只是作为线程类的静态成员添加,则这一点可能不够清晰。详情请见http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2320.html

2

std::thread 用于创建、监控和操作新线程
std::this_thread 用于已创建的线程内部。

您可以将 this_thread 提供为位于 std::thread 内的公共类的静态方法,但这是一种设计决策。我敢说,这种设计更像是Java风格,而将数据封装为命名空间则更符合C++哲学调整的设计。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接