0

So, I have this code that doesn't seem to work: (more details below)

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

Basically, it has a function that takes two arguments: a number (to distinguish which thread called it) and a integer variable "count" passed by reference. The idea is that each thread is supposed to increase the value of count when it runs. However, the result is that it increases its own version of count so the result is:

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

Instead of each thread increasing count to the next number:

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

If I run this code by simply calling this function twice, it works as intended. If I use threads, it doesn't.

Complete beginner here. Any insight on why I'm stupid?

William Northern
  • 403
  • 2
  • 5
  • 12

2 Answers2

2

It's the boost::bind that does not resolve the int to a reference. You need to use the reference-wrapper so:

boost::bind( incr1, 1, boost::ref(count) );
CashCow
  • 30,981
  • 5
  • 61
  • 92
1

Because you need to use boost::ref to pass something by reference through boost::bind.

boost::thread th1(boost::bind(incr1,1,boost::ref(count)));
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415