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

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

C++11 thread(1)普通に使う(引数とか)

Sponsored Links

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

さて、今日はC++11に搭載されたthreadについて
これが便利なところはOSによって処理を行う関数が異なっていたのを
threadライブラリが賄ってくれるという素晴らしきかな。

普通に使う

#include <iostream>
#include <thread>

using namespace std;

void work(){
	for(int i = 0; i < 10; i++){
		cout << std::this_thread::get_id() << " hello world" << endl;
	}
}

int main(int argc, char const *argv[]){
	thread th(work);

	th.join();
	return 0;
}


出力

0x1032bf000 hello world
0x1032bf000 hello world
0x1032bf000 hello world
0x1032bf000 hello world
0x1032bf000 hello world
0x1032bf000 hello world
0x1032bf000 hello world
0x1032bf000 hello world
0x1032bf000 hello world
0x1032bf000 hello world

th.joinでスレッド終了まで待機させています。

スレッドを2つ生成してみる

#include <iostream>
#include <thread>

using namespace std;

void work(){
	for(int i = 0; i < 10; i++){
		cout << std::this_thread::get_id() << " hello world" << endl;
	}
}

void work2(){
	for(int i = 0; i < 10; i++){
		cout << std::this_thread::get_id() << " good bye world" << endl;
  	}
}

int main(int argc, char const *argv[]){
	thread th(work);
	thread th2(work2);

	th.join();
	th2.join();
	return 0;
}

出力

00xx1100cc881947000000 hello wo rglodo
d 0bxy1e0 cw8o1r4l0d0
0 0hxe1l0lco8 9w7o0r0l0d 
go0oxd1 0bcy8e1 4w0o0r0l dh
el0lxo1 0wco8r9l7d0
000 xg1o0ocd8 1b4y0e0 0w ohrelldl
o 0wxo1r0lcd8
9700x0100 cg8o1o4d0 0b0y eh ewlolrol dw
or0lxd1
0c08x91700c0801 4g0o0o0d  hbeylel ow owrolrdl
d
0x01x01c08c9871040000 0g ohoedl lboy ew owrolrdl
d
0x01x01c08c1849070000 0h eglolood  wboyrel dw
or0lxd1
0c08x11400c0809 7h0e0l0l og owoodr lbdy
e 0wxo1r0lcd8
1400x0100 ch8e9l7l0o0 0w ogrolodd
 bye world
0x10c897000 good bye world

もうカオスですね。一つが出力が行っている間にもう一つも出力してもう何が何だがわからない状態。

引数有り

#include <iostream>
#include <thread>

using namespace std;

void work(int a,int b){
	for(int i = 0; i < 10; i++){
		cout << std::this_thread::get_id() << " " << a+b << endl;
	}
}

int main(int argc, char const *argv[]){
	thread th(work,10,20);

	th.join();
	return 0;
}

出力

0x1050f1000 30
0x1050f1000 30
0x1050f1000 30
0x1050f1000 30
0x1050f1000 30
0x1050f1000 30
0x1050f1000 30
0x1050f1000 30
0x1050f1000 30
0x1050f1000 30

因みに通常なら-std=c++11のオプションが不要なmervericksですが、
この時はつけないとエラーが出ます。つまりコンパイルオプションは

g++ -std=c++11 thread.cpp

関数以外に引数を渡すことで実現しています。

参照渡し

#include <iostream>
#include <thread>

using namespace std;

void work(int &num){
	for(int i = 0; i < 10; i++){
		num++;
	}
}

int main(int argc, char const *argv[]){
	int num = 200;
	thread th(work,ref(num));

	th.join();
	cout << num << endl;
	return 0;
}

出力

210

std::ref()で変数を入れてあげるとこうなる。