sowmya m
sowmya m

Reputation: 1

Synchronising main thread and worker thread

In QT, from main(GUI) thread I am creating a worker thread to perform a certain operation which accesses a resource shared by both threads. On certain action in GUI, main thread has to manipulate the resource. I tried using QMutex to lock that particular resource. This resource is continuously used by the worker thread, How to notify main thread on this? Tried using QWaitCondition but it was crashing the application.

Is there any other option to notify and achieve synchronisation between threads? Attached the code snippet.

void WorkerThread::IncrementCounter()
{
    qDebug() << "In Worker Thread IncrementCounter function" << endl;
    while(stop == false)
    {
        mutex.lock();
        for(int i = 0; i < 100; i++)
        {
            for(int j = 0; j < 100; j++)
            {
                counter++;
            }
        }

        qDebug() << counter;
        mutex.unlock();
    }
    qDebug() << "In Worker Thread Aborting " << endl;
}

//Manipulating the counter value by main thread.
void WorkerThread::setCounter(int value)
{
    waitCondition.wait(&mutex);
    counter = value;
    waitCondition.notify_one();
}

Upvotes: 0

Views: 295

Answers (2)

CodeLurker
CodeLurker

Reputation: 1371

You could use shared memory from within the same process. Each thread could lock it before writing it, like this:

QSharedMemory *shared=new QSharedMemory("Test Shared Memory");

if(shared->create(1,QSharedMemory::ReadWrite))
{
    shared->lock();

    // Copy some data to it
    char *to = (char*)shared->data();
    const char *from = &dataBuffer;
    memcpy(to, from, dataSize);

    shared->unlock();
}

You should also lock it for reading. If strings are wanted, reading strings can be easier that writing them, if they are zero terminated. You'll want to convert .toLatin1() to get a zero-terminated string which you can get the size of a string. You might get a lock that multiple threads can read from, with shared->attach(); but that's more for reading the shared memory of a different process..

You might just use this instead of muteces. I think if you try to lock it, and something else already has it locked, it will just block until the other process unlocks it.

Upvotes: 0

TheSHEEEP
TheSHEEEP

Reputation: 3132

You are using the wait condition completely wrong. I urge you to read up on mutexes and conditions, and maybe look at some examples.

wait() will block execution until either notify_one() or notify_all() is called somewhere. Which of course cannot happen in your code.
You cannot wait() a condition on one line and then expect the next two lines to ever be called if they contain the only wake up calls.

What you want is to wait() in one thread and notify_XXX() in another.

Upvotes: 2

Related Questions