Kranthi
Kranthi

Reputation: 195

Poco thread synchronization issue

The following is Sample Poco thread program to understand mutex and thread syncronization. Still seeing different outputs for the same program.

#include "Poco/ThreadPool.h"
#include "Poco/Thread.h"
#include "Poco/Runnable.h"
#include "Poco/Mutex.h"
#include <iostream>
#include <unistd.h>
using namespace std;

class HelloRunnable: public Poco::Runnable
{
    public:
        static int a;
        HelloRunnable(){
        }
        HelloRunnable(unsigned long n):_tID(n){
        }
        void run()
        {
            Poco::Mutex::ScopedLock lock(_mutex);
            std::cout << "==>> In Mutex thread " << _tID << endl;
            int i;
            for (i=0;i<50000;i++)
            {
                a = a+1;
            }
            Poco::Mutex::ScopedLock unlock(_mutex);
        }
    private:
        unsigned long _tID;
        Poco::Mutex _mutex;
};
int HelloRunnable::a = 0;
int main(int argc, char** argv)
{
    Poco::Thread thread1("one"), thread2("two"), thread3("three");

    HelloRunnable runnable1(thread1.id());
    HelloRunnable runnable2(thread2.id());
    HelloRunnable runnable3(thread3.id());

    thread1.start(runnable1);
    thread2.start(runnable2);
    thread3.start(runnable3);

    thread1.join();
    thread2.join();
    thread3.join();
    cout << "****>> Done and a: " << HelloRunnable::a  << endl;
    return 0;
}

Getting the outputs as follows:

OutPut1:

==>> In Mutex thread 1
==>> In Mutex thread 2
==>> In Mutex thread 3
****>> Done and a: 142436

OutPut2:

==>> In Mutex thread 2==>> In Mutex thread 3

==>> In Mutex thread 1
****>> Done and a: 143671

OutPut3:

==>> In Mutex thread 2
==>> In Mutex thread 3
==>> In Mutex thread 1
****>> Done and a: 150000

I always expecting OutPut3 as the result. What is the issue in above program?

Upvotes: 0

Views: 1610

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409296

The mutex is a non-static member variable of the class, which means each instance of the class will have its own mutex. If you want synchronization the mutex needs to be shared between the threads. You need to make it static.

Also in the run function the variable unlock doesn't do anything. The object lock will unlock the mutex when it goes out of scope which is when the function returns.

Upvotes: 5

Related Questions