C++11 Std::thread

Source: Internet
Author: User

C in the same application of the Pthread library is not to repeat, only discuss std::thread

The thread added in c++11 requires a compiler support of at least gcc4.7.0. Compile and install GCC note the online article.

#include <unistd.h><iostream><thread>//using namespace std; void Thread_func () {    "" << std::this_thread::get_id () << std:: Endl;} int Main () {    std::thread thread1 (thread_func);    Thread1.join ();     return 0 ;}
View Code

1, + + thread.cc-wall-pthread-std=c++11-o THREAD//STD::p thread compile, you also need to add-pthread ... S

Use STD::THIS_THREAD::GET_ID () to get ThreadID. http://www.cplusplus.com/reference/thread/this_thread/

2. Std::thread's executor does not require a normal function, and any callable (callable) object can be

Use lambda expression: Std::thread thread1 ([] (int a, int b) {std::cout << a << "+" << b << "=" << A + b& lt;< Std::endl;}, 1, 2);

3. Wait for thread to end

Threads are divided into separate or joinable states, and thread has a member function joinable can determine whether it can be joinable. If joiable = = True at the time of the destructor causes

Terminat () is called.

The default constructor object does not represent any thread, so joinable is false, the call to the join is false, and the detach is called;

4. In addition to the Std::thread member function, the external Std::this_thread namespace defines a series of functions for managing the current thread.

Reference: Https://blog.poxiao.me/p/multi-threading-in-cpp11-part-1-thread-and-future/

C++11 Std::thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.