Std :: thread class vs std :: this_thread namespace in C ++?

If we already have the std::thread class, then why do we need the std::this_thread ?

What are the main differences between them?

When should I use the std::thread class and when is the std::this_thread namespace?

+5
source share
2 answers

The groups of this_thread namespaces that access the current thread, so when we need to do something in the current thread, we don’t need access to the thread object.

The thread class does not provide access for the ledge and sleep, these functions make sense only for the current thread and therefore can be found in the this_thread namespace.

If we need information about another thread, we need a thread instance of this thread, if we need to access the current thread, we can always do this using functions in the this_thread namespace.

Thoughts on using the this_thread namespace this_thread also explained in the draft extension:

this is the namespace this_thread

Note the use of the this_thread namespace to disambiguate when you request the identifier for the current thread, as well as the identifier of the child thread. The name get_id for this action remains the same in the interest of reducing the conceptual footprint of the interface. This construct also applies to the cancelation_requested function:

 std::thread my_child_thread(f); typedef std::thread::id ID: ID my_id std::this_thread::get_id(); // The current thread id ID your_id my_child_thread.get_id(); // The child thread id bool have_i_been_canceled = std::this_thread::cancellation_requested(); // Current thread cancellation status bool have_you_been_canceled = my_child_thread.cancellation_requested(); // Child thread cancellation status 

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2320.html

Adding functions from the this_thread namespace as static members of the thread class could be done, but then the get_id function should be called something else so that it clearly differs from the already existing get_id function of the thread class. In other words, I assume that the C ++ team decided to add functions to a separate namespace so that it is more clear that these functions read or process the current thread, which would not be equally clear if they were just added as static members of the class streams.

+5
source

std::thread used to create, monitor and manage new threads ,
std::this_thread used inside alreay of created threads .

You could provide this_thread as static methods inside an open class inside std::thread , but this is a design decision, I would dare to say that this kind of design is more like Java, where encapsulating data as namespace is more C ++ - the philosophy is custom construction .

+2
source

Source: https://habr.com/ru/post/1236545/


All Articles