【C++学習記】その八、C++マルチスレッドの基礎

記事ディレクトリ

1。概要

このヘッダー ファイルを追加すると、スレッド関連の操作を直接呼び出すことができます。

#include <thread>

対応する CMakeLists.txt コンパイルを追加する必要があります

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

std::thread デフォルト コンストラクターは、空の std::thread 実行オブジェクトを作成します。

std::thread thread_object(callable)

その呼び出しオブジェクトは、次の 3 つのタイプのいずれかになります。

  • 関数ポインタ
  • 関数オブジェクト
  • ラムダ式

プログラムのソースコードは次のとおりです。

#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;
}

上記の実際の印刷結果は汚くなります。

実際のプロジェクトでの使用は、多くの場合、より複雑です。

2 つのインスタンス

バックグラウンド:

ここには 2 つのクラスがあり、1 つは blueEarModel が abstractModel を継承するクラスです。
詳細なコードは次のとおりです。

#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;
}

ここでは、匿名関数を使用して両方のスレッドを作成します。
実際、印刷物は汚いです。
動作させるには、関連するロックを後で追加する必要があります。

おすすめ

転載: blog.csdn.net/qq_38753749/article/details/129834065