为什么要使用std::this_thread命名空间?可不可以将该命名空间中的成员实现为std::thread类的静态成员?
为什么要使用std::this_thread命名空间?可不可以将该命名空间中的成员实现为std::thread类的静态成员?
从原始提案中,无论你是为自己还是为子线程获取thread::id
,获取的方式都是通过get_id()
来实现:
请注意使用
this_thread
命名空间以消除在请求当前线程的ID与子线程的ID时的歧义。在接口概念上保持一致性,此操作的get_id
名称保持不变。
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
因此,this_thread
命名空间是一种可读性强的方式来区分两个线程,同时保持概念接口最小化(获取线程 ID 的名称相同)。
以下是可能的替代设计:
struct thread
{
static int get_id() {return 1;}
int get_id() const {return 2;}
};
test.cpp:4:9: error: static and non-static member functions with the same parameter types cannot be overloaded
int get_id() const {return 2;}
^
test.cpp:3:16: note: previous declaration is here
static int get_id() {return 1;}
^
1 error generated.
另一种设计方式会给静态成员起不同的名称。但现在接口更大了。原始提案也以完全相同的方式处理了另一个函数:
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
命名空间来查询当前线程即可。不幸的是,在标准化过程中,委员会取消了线程取消。
get_id
是获取当前线程ID的静态成员函数,则my_child_thread.get_id()
调用该静态成员函数。请参见http://codepad.org/JRTvzDLk以获取简化示例。(顺便说一句,这不是我自己想出来的,有人在一个小时前的评论中写了这个!) - user395760