既然我们已经有了 std::thread
类,为什么还需要 std::this_thread
命名空间?
它们之间的基本区别是什么?
我应该在什么情况下使用 std::thread
类以及何时使用 std::this_thread
命名空间?
既然我们已经有了 std::thread
类,为什么还需要 std::this_thread
命名空间?
它们之间的基本区别是什么?
我应该在什么情况下使用 std::thread
类以及何时使用 std::this_thread
命名空间?
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。std::thread
用于创建、监控和操作新线程,
std::this_thread
用于已创建的线程内部。
您可以将 this_thread
提供为位于 std::thread
内的公共类的静态方法,但这是一种设计决策。我敢说,这种设计更像是Java风格,而将数据封装为命名空间则更符合C++哲学调整的设计。
std::thread
的功能基本不同。你能更具体地说明一下,你实际上不清楚什么吗? - πάντα ῥεῖ