だから、私は動作していないように見えるこのコードを持っています: (詳細は以下)
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <Windows.h>
using namespace std;
boost::mutex m1,m2;
void * incr1(int thr, int& count) {
for (;;) {
m1.lock();
++count;
cout << "Thread " << thr << " increased COUNT to: " << count << endl;
m1.unlock();
//Sleep(100);
if (count == 10) {
break;
}
}
return NULL;
}
int main() {
int count = 0;
boost::thread th1(boost::bind(incr1,1,count));
boost::thread th2(boost::bind(incr1,2,count));
th1.join();
th2.join();
system("pause");
return 0;
}
基本的に、2 つの引数を取る関数があります。数値 (どのスレッドが呼び出したかを区別するため) と、参照によって渡される整数変数 "count" です。アイデアは、各スレッドが実行時に count の値を増やすことになっているということです。ただし、その結果、count の独自のバージョンが増加するため、結果は次のようになります。
Thread 1 increased count to 1
Thread 2 increased count to 1
Thread 1 increased count to 2
Thread 2 increased count to 2
Thread 1 increased count to 3
Thread 2 increased count to 3
各スレッドがカウントを次の数に増やす代わりに:
Thread 1 increased count to 1
Thread 2 increased count to 2
Thread 1 increased count to 3
Thread 2 increased count to 4
Thread 1 increased count to 5
Thread 2 increased count to 6
この関数を 2 回呼び出すだけでこのコードを実行すると、意図したとおりに機能します。スレッドを使用する場合、使用しません。
完全初心者はこちら。なぜ私が愚かなのかについての洞察はありますか?