为什么是std :: this_thread命名空间? [英] Why the std::this_thread namespace?
问题描述
std :: this_thread命名空间有技术原因吗?为什么这个命名空间的成员没有实现为std :: thread类的静态成员?
Is there a technical reason for the std::this_thread namespace? Why could the members of this namespace not have been implemented as static members of the std::thread class?
推荐答案
href =http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2184.html =nofollow>原始提案,获取方法 thread :: id
拼写 get_id()
是否获得 thread :: id
为自己或子线程:
From the original proposal, the way to get a thread::id
is spelled get_id()
whether you are getting the thread::id
for yourself, or for a child thread:
注意使用
this_thread
命名空间来消除歧义,当你是
请求当前线程的id,而子线程的id。
该操作的get_id
名称保持不变,有利于
减少接口的概念足迹。
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. Theget_id
name for this action remains the same in the interest of reducing the conceptual footprint of the interface.
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
命名空间是一种可读的方式来区分两者,同时将概念界面保持最小(获取线程标识的名称相同)。
Thus the this_thread
namespace is a readable way to differentiate between the two, while keeping the conceptual interface to a minimum (same name for getting a thread id).
这里有一个可能的替代设计:
Here's a possible alternative design:
struct thread
{
static int get_id() {return 1;}
int get_id() const {return 2;}
};
此设计的一个缺点是它不能编译:
One disadvantage of this design is that it does not compile:
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.
另一种设计会给静态成员一个不同的名称。但现在的界面更大了。原来的建议也处理另一个函数完全相同的方式:
Another design would have given the static member a different name. But now the interface is bigger. The original proposal also treated another function the exact same way:
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
命名空间,如果他们想查询当前线程。不幸的是,委员会在标准化期间取消了线程取消。
Thus it made a lot of sense to reuse the names so clients don't have to learn so many names. They just need to learn to use the this_thread
namespace if they want to query the current thread. Unfortunately the committee removed thread cancellation during standardization.
这篇关于为什么是std :: this_thread命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!