0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C++のThreadで並列処理

0
Posted at

研究で行うシミュレーションの計算時間が長かったので、並列処理を実装しました。メモ程度に記しておきます。

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

void print_a(){ for(long long i=0; i<100; i++) if(i >95) cout << "A"; }
void print_b(){ for(long long i=0; i<100; i++) if(i >95) cout << "B"; }

int main(){
    thread th_print_a(print_a); // スレッドを立ち上げ
    thread th_print_b(print_b);

    th_print_a.join(); // スレッドの処理が終わるまで待つ
    th_print_b.join();

    cout << "Fin" << endl;

    return 0;
}

実行結果

AABBBBAAFin

こんな感じで各スレッドが順番に実行され、全ての実行が終わってからFinが出力されている様子が分かります。

ちなみにオブジェクト内の関数をthreadで利用したい場合には、

std::thread th_test([this]() { this->test_function(); });

こんな感じで実装できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?