2013-03-05 54 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));