[C++ study notes] Eight, the basis of C++ multithreading

Article Directory

1 Overview

Adding this header file can directly call thread-related operations

#include <thread>

And need to add in the corresponding CMakeLists.txt compilation

set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11 -pthread")

std::thread default constructor, creates an empty std::thread execution object.

std::thread thread_object(callable)

Its calling object can be any of the following three types:

  • function pointer
  • function object
  • lambda expression

The source code of the program is as follows:

#include <iostream>
#include <thread>
using namespace std;

void foo(int Z)
{
    
    
    cout << "线程ID" << this_thread::get_id() << endl;
    cout << "线程使用函数指针作为可调用参数 传入参数为 " << Z << endl;
}

// 可调用对象
class thread_obj {
    
    
public:
    void operator()(int x)
    {
    
    
        cout << "线程ID" << this_thread::get_id() << endl;
        cout << "线程使用可调用对象作为可调用参数 传入参数为 " << x << endl;
    }
};

int main()
{
    
    
    // 函数指针
    thread th1(foo, 1);

    // 函数对象
    thread th2(thread_obj(), 2);

    // 定义 Lambda 表达式
    auto f = [](int x) 
    {
    
    
        cout << "线程ID" << this_thread::get_id() << endl;
        cout << "线程使用 lambda ";
        for (int i = 0; i < x; i++)
        {
    
    
            cout << "i = " << i << "\t";
        }
        cout << endl;
    };

    thread th3(f, 3);

    th1.join();
    th2.join();
    th3.join();
    return 0;
}

The above actual printed results will be messy.

The use in actual projects is often more complicated.

2 instances

background:

I have two classes here. One is that blueEarModel inherits from abstractModel.
The detailed code is as follows:

#include <iostream>
#include <thread>
#include <abstractModel.h>
#include <blueEarModel.h>
using namespace std;

int main()
{
    
    
    //创建对应的线程
    thread th1([]{
    
    
        blueEarModel  blueEarModelPri;
    });

    thread th2([]{
    
    
        abstractModel  abstractModelPri;
    });

    th1.join();
    th2.join();

    return 0;
}

Here, an anonymous function is used to create the threads of both.
In fact, the printout is messy.
Relevant locks need to be added later to operate.

Guess you like

Origin blog.csdn.net/qq_38753749/article/details/129834065