のんびりしているエンジニアの日記

ソフトウェアなどのエンジニア的な何かを書きます。

C++11 thread(2) mutex。さぁレッツマルチスレッド!

Sponsored Links

皆さんこんにちは
お元気ですか?私は元気です。

さて、今回はmutexで使うlockについて

まずはこのプログラムを動かしてみましょう。

mutex_lock

mutexとは

複数のスレッドで動作させるときに
他に影響を与えたくない場合にロックをかけ、侵入できるスレッドを一つにする。

ソースコード

#include <iostream>
#include <thread>
#include <mutex>

using namespace std;
std::mutex mtx;

void print_thread_id (int id) {
  //mtx.lock();
  cout << "thread #" << id << endl;
  //mtx.unlock();
}

int main(int argc, char const *argv[])
{
  thread threads[10];
  for (int i=0; i<10; ++i)
    threads[i] = std::thread(print_thread_id,i+1);

  for (auto& th : threads) th.join();

  return 0;
}

出力

thread #1
thread #2
thread #4
ttttttthhhhhhhrrrrrrreeeeeeeaaaaaaaddddddd       #######3567891

print_thread_idのコメントを外してみましょう。
すると、以下のような出力になります。

thread #1
thread #2
thread #3
thread #4
thread #5
thread #6
thread #7
thread #8
thread #10
thread #9

lockをかけたところからlockを外すまでは同じ関数を動作させることができません。
まぁその関数の動作はひとつのみってことですね。

これらを使ってうまく高速化してひゃっほーいするのが良いのでしょう。きっと