2013-03-05 8 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; 
} 

을,이 2 개 개의 인수를 취하는 기능을 가지고하십시오 number (참조하는 스레드를 구별하기 위해)와 정수 변수 "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 

이 코드에 의해 실행하는 경우 단순히이 함수를 두 번 호출하면 의도 한대로 작동합니다. 쓰레드를 사용하면 그렇지 않습니다.

완전한 초보자는 여기에 있습니다. 왜 내가 어리 석까요?

답변

1

boost::bind을 통해 참조로 항목을 전달하려면 boost::ref을 사용해야합니다.

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

Worked! 감사. –

2

참조를 해석하지 않는 것은 boost::bind입니다. 참조 래퍼를 사용해야하므로 :

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