Search code examples
c++c++11library-design

Why the std::this_thread namespace?


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?


Solution

  • 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.