前の記事では引数なしの関数でスレッドを生成したが、それで事足りるわけはないので、今回は引数付きの関数を渡してスレッドを生成する。ドキュメントによるとboost::bindをつかってできるよっぽいことが書いてあるので、よく考えずbindを使って関数オブジェクトを渡してみる。ソースは次の通り。
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <cstdlib>
- #include <ctime>
- #include <boost/thread.hpp>
- #include <boost/bind.hpp>
- using namespace std;
- using namespace boost;
- void writeMsg(string str){
- time_t clock;
- for (int i = 0; i < 100; i++){
- time(&clock);
- cout << str << ": " << ctime(&clock);
- for(int j = 0; j < 10000; j++){
- for(int k = 0; k < 10000; k++){
- int a = j * k;
- }
- }
- }
- }
- int main()
- {
- string thName1="Thread 1";
- string thName2="Thread 2";
- thread thWriteMsg1(bind(&writeMsg, thName1));
- thread thWriteMsg2(bind(&writeMsg, thName2));
- time_t clock;
- for (int i = 0; i < 100; i++){
- time(&clock);
- cout << "MAIN: " << ctime(&clock);
- for(int j = 0; j < 10000; j++){
- for(int k = 0; k < 10000; k++){
- int a = j * k;
- }
- }
- }
- thWriteMsg1.join();
- thWriteMsg2.join();
- return EXIT_SUCCESS;
- }
前回のソースをちょこっと変更して文字列引数をとるようにした。関数側は「引数文字列: 時間」と出力し、メイン関数は相変わらず「MAIN: 時間」と出力する。実際に動かすとこんな感じ。
MAIN: Sun Feb 6 14:46:52 2011
Thread 2: Sun Feb 6 14:46:52 2011
Thread 1: Sun Feb 6 14:46:53 2011
MAIN: Sun Feb 6 14:46:53 2011
Thread 2: Sun Feb 6 14:46:53 2011
Thread 1: Sun Feb 6 14:46:53 2011
Thread 2: Sun Feb 6 14:46:53 2011
MAIN: Sun Feb 6 14:46:53 2011
Thread 1: Sun Feb 6 14:46:54 2011
Thread 2: Sun Feb 6 14:46:54 2011
MAIN: Sun Feb 6 14:46:54 2011
MAIN: Sun Feb 6 14:46:55 2011
MAIN: Sun Feb 6 14:46:55 2011
MAIN: Sun Feb 6 14:46:55 2011
どうやらうまく動いているようだ。
ドキュメントをよく見てみると「Thread Constructor with arguments」というものがいる。それによると、「thread(関数ポインタ, 引数1, 引数2, ...)」としてもOKらしい。というわけで次のようにソースを変更してみた。
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <cstdlib>
- #include <ctime>
- #include <boost/thread.hpp>
- using namespace std;
- using namespace boost;
- void writeMsg(string str){
- time_t clock;
- for (int i = 0; i < 100; i++){
- time(&clock);
- cout << str << ": " << ctime(&clock);
- for(int j = 0; j < 10000; j++){
- for(int k = 0; k < 10000; k++){
- int a = j * k;
- }
- }
- }
- }
- int main()
- {
- string thName1="Thread 1";
- string thName2="Thread 2";
- thread thWriteMsg1(&writeMsg, thName1);
- thread thWriteMsg2(&writeMsg, thName2);
- time_t clock;
- for (int i = 0; i < 100; i++){
- time(&clock);
- cout << "MAIN: " << ctime(&clock);
- for(int j = 0; j < 10000; j++){
- for(int k = 0; k < 10000; k++){
- int a = j * k;
- }
- }
- }
- thWriteMsg1.join();
- thWriteMsg2.join();
- return EXIT_SUCCESS;
- }
実際の動きは「testThread2」と同じになる。今のところ、どちらの方法を使うかは好みかなと思っているが、複雑になってきたらboost::bindを使ってオブジェクトかしといた方が管理が楽になるのだろうかと思っている。
コメント