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”。这个想法是每个线程都应该在运行时增加 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

如果我通过简单地调用此函数两次来运行此代码,它会按预期工作。如果我使用线程,它不会。

完整的初学者在这里。关于我为什么愚蠢的任何见解?

4

2 回答 2

2

boost::bind不能将 int 解析为引用。您需要使用参考包装器:

boost::bind( incr1, 1, boost::ref(count) );
于 2013-03-05T16:24:18.403 回答
1

因为你需要使用boost::ref通过引用传递一些东西boost::bind

boost::thread th1(boost::bind(incr1,1,boost::ref(count)));
于 2013-03-05T16:23:53.720 回答