2013-03-05 55 views
0

所以,我有這樣的代碼似乎並不工作:(更多詳情如下)升壓線程不會增加值正確

#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; 
} 

基本上,它有一個函數有兩個參數:一個數字(區分哪個線程調用它)和通過引用傳遞的整數變量「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 

如果我運行此代碼由簡單地調用這個函數兩次,它按預期工作。如果我使用線程,它不會。

完整的初學者在這裏。任何洞悉我爲什麼愚蠢?

回答

1

因爲您需要使用boost::ref才能通過boost::bind引用來傳遞某些內容。

boost::thread th1(boost::bind(incr1,1,boost::ref(count))); 
+0

工作!謝謝。 – 2013-03-05 16:26:27

2

這是boost::bind,它不會將int解析爲引用。您需要使用參考包裝紙:

boost::bind(incr1, 1, boost::ref(count));