Boost logo

Boost Users :

Subject: [Boost-users] Fw: Use of QMutex not as expected
From: Don El Ron (donelron_at_[hidden])
Date: 2015-08-25 07:31:44

Dear all,
I use the following code:

#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>
class myRessource{
    myRessource() : m_iValue(0){}
    //copy ctor necessary, so a member of type boost::mutex is possible in this class
    myRessource(const myRessource &copyRes) : m_iValue(0){}     
    void SendCommand(int ival){
        std::cout << "resource update to " << ival << " active count is " << myMutex.active_count << std::endl;
    int m_iValue;
    boost::mutex myMutex;

int iSleepTime1=200;
int iSleepTime2=30;

class myWorker1
    myWorker1(myRessource res): m_res(res){}
    void DoWork(void){
        m_res.SendCommand(1);     boost::this_thread::sleep(boost::posix_time::milliseconds(iSleepTime1));
        m_res.SendCommand(2);     boost::this_thread::sleep(boost::posix_time::milliseconds(iSleepTime1));
        m_res.SendCommand(3);     boost::this_thread::sleep(boost::posix_time::milliseconds(iSleepTime1));
        m_res.SendCommand(4);     boost::this_thread::sleep(boost::posix_time::milliseconds(iSleepTime1));
    myRessource m_res;

class myWorker2
    myWorker2(myRessource res): m_res(res){}
    void DoWork(void){
        m_res.SendCommand(201);     boost::this_thread::sleep(boost::posix_time::milliseconds(iSleepTime2));
        m_res.SendCommand(202);     boost::this_thread::sleep(boost::posix_time::milliseconds(iSleepTime2));
        m_res.SendCommand(203);     boost::this_thread::sleep(boost::posix_time::milliseconds(iSleepTime2));
        m_res.SendCommand(204);     boost::this_thread::sleep(boost::posix_time::milliseconds(iSleepTime2));
    myRessource m_res;
int main(int argc, char *argv[])
    myRessource r;
    myWorker1 w1(r);
    boost::thread workerThread1(&myWorker1::DoWork, &w1);
    myWorker2 w2(r);
    boost::thread workerThread2(&myWorker2::DoWork, &w2);
This results in the following output (no formatting, e.g. line breaks done):

resource update to resource update to 201 active count is -21474836481 active co
unt is -2147483648
resource update to 202 active count is -2147483648
resource update to 203 active count is -2147483648
resource update to 204 active count is -2147483648
resource update to 2 active count is -2147483648
resource update to 3 active count is -2147483648
resource update to 4 active count is -2147483648
The output always looks like this, i. e. the first two lines are "merged", whereas the remaining lines look just fine.
Why does this happen and what do I have to do in order to correct my mistake???
Many thanks in advance!

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at