dovahin
dovahin

Reputation: 133

Passing objects to multithreading objects Qt

I wonder is it thread safe to pass another objects to the object that runs in another thread than GUI thread. I mean by that is it thread safe to do something like that? What is happening with this example object through the lifetime of the app?

In worker.h file

private:
Example* example;

In worker.c file

Worker::Worker(QObject *parent, Example *example) :
QObject(parent),
example(example)
{

}

In main.c

Example example(nullptr);
auto worker = new Worker(nullptr, &example);
auto thread = new QThread;
Printer printer;

QObject::connect(thread, &QThread::started, worker, &Worker::doWork);
QObject::connect(worker, &Worker::readedText, &printer, &Printer::printMessage);
QObject::connect(worker, &Worker::workDone, thread, &QThread::quit);
QObject::connect(thread, &QThread::finished, worker, &Worker::deleteLater);

worker->moveToThread(thread);
thread->start();

And what if GUI thread would have to use an Example object since i'm passing the pointer to that object?

Upvotes: 0

Views: 345

Answers (1)

AlexG
AlexG

Reputation: 1103

Generally speaking, there is nothing wrong passing objects to different threads, as long as you make sure there's some kind of mechanism to deal with concurrency issues while reading/writing to that object. The most simplest way of doing that is through the use of condition variable / mutex that acquires (locks) the object when it is in use. Other threads will wait until the lock is no longer in use so they can have a hold of it.

The code you wrote isn't working. 'example' is a local variable and will be deleted when the function returns. You need to make sure the lifetime of your variables always exceeds their usage. You might want your thread to hold a smart pointer such as std::shared_ptr pointing to a dynamically allocated object.

Upvotes: 1

Related Questions