Three methods of C++11 multi-thread creation

  In every C++ application, there is a main thread (main function). In the C++11 standard, creating threads can be created through the class std::thread. This class needs to include header files:

To initialize std::thread class object, there are three ways to pass parameters:

  Function pointer class object lambda expression
  
  

For example, you can create a thread object like this: After the
Insert picture description here
thread object is created, the passed callback function can be executed in parallel.
If you want to wait for all threads to end and then exit before exiting, you can use the join() function.
What if the threads are distinguished during the running process?

  Each thread has its own thread ID. The thread created by std::thread can use std::thread::get_id() to get the thread ID.

For example, get the current thread ID:

  std::this_thread::get_id()

If std::thread is not associated with any thread object, then get_id() will return a std::thread default constructor object.

1. Use function pointers to create threads

Insert picture description here
Operation result:
Insert picture description here
Attach example code:

//小问学编程
#include<iostream>
#include<thread>
using namespace std;

void thread_function()
{
    
    
    for(int i=0;i<10000;i++)
        cout<<"thread function Executing"<<endl;
}

int main()
{
    
    
    thread threadObj(thread_function);
    for(int i=0;i<10000;i++)
        cout<<"Display From MainThread"<<endl;
    threadObj.join();
    cout<<"Exit of Main function"<<endl;
    return 0;
}

2. Use class objects to create threads

Insert picture description here
Operation result:
Insert picture description here
Attach example code:

//小问学编程
#include<iostream>
#include<thread>
using namespace std;

class DisplayThread
{
    
    
public:
	void operator()()
	{
    
    
    for(int i=0;i<10000;i++)
        cout<<"thread function Executing"<<endl;
	}
};

int main()
{
    
    
    thread threadObj((DisplayThread()));
    for(int i=0;i<10000;i++)
        cout<<"Display From MainThread"<<endl;
    threadObj.join();
    cout<<"Exit of Main function"<<endl;
    return 0;
}

3. Use lambda to create threads

Insert picture description here
operation result:
Insert picture description here

Attach example code:

//小问学编程
#include<iostream>
#include<thread>
using namespace std;

int main()
{
    
    
    int x=9;
    thread threadObj([]{
    
    
        for(int i=0;i<10000;i++)
            cout<<"Display Thread Executing"<<endl;
                     });
    for(int i=0;i<10000;i++)
        cout<<"Display From Main Thread"<<endl;
    threadObj.join();
    cout<<"Exiting from Main Thread"<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43297891/article/details/113821892