Why the std::this_thread namespace? [closed]

梦想的初衷 提交于 2019-12-10 06:34:15

问题


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?


回答1:


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:

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.

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

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

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.



来源:https://stackoverflow.com/questions/15032692/why-the-stdthis-thread-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!