简体   繁体   English

在Qt中同步不同线程中的对象

[英]Synchronizing Objects in Different Threads in Qt

Right now in Qt I am faced with the problem where I have 2 threads that have 2 different objects. 现在在Qt我面临的问题是我有2个线程有2个不同的对象。 These objects are not QObjects, thus they are not able to communicate using Signals/Slots. 这些对象不是QObject,因此它们无法使用Signals / Slots进行通信。 The first thread is the primary thread, and the second thread is in a infinite loop, which process command objects using a queue. 第一个线程是主线程,第二个线程是无限循环,它使用队列处理命令对象。

The main thread must wait for the processing thread to finish the request. 主线程必须等待处理线程完成请求。

How would I go about synchronizing the two different threads without using global mutex, and wait conditions? 如何在不使用全局互斥锁和等待条件的情况下同步两个不同的线程?

You could use mutexes. 你可以使用互斥锁。 Lock everytime you pull "request" from queue, and lock everytime you want to append to queue. 每次从队列中提取“请求”时锁定,并在每次要追加到队列时锁定。 This way you may have 这样你就可以了

something like this: 这样的事情:

#include <QMutex>
#include <QWaitCondition>

class processingThread
{
public:
    void appendToQueue(Request req)
    {
       sync.lock();
       queue.append(req);
       sync.unlock();
       cond.wakeAll();            
    }

protected:
    void run()
    {
        while(1)
        {
           sync.lock();
           QWaitCondition wait(&sync);
           Request current = queue.takeFirst();

           // process request

           sync.unlock()
        }
    }

private:
    QList<Request> queue;
    QMutex sync;
    QWaitCondition cond;
};

You can now call processingThread::appendToQueue from any thread and get data synchronized. 您现在可以从任何线程调用processingThread :: appendToQueue并获取数据同步。 You can use this pattern to sync any data within thread. 您可以使用此模式同步线程中的任何数据。 Just remember to lock any access to data you want sync. 只需记住锁定您想要同步的数据的任何访问权限。 Note that QWaitCondition is only to make your thread work only when needed 请注意,QWaitCondition仅用于在需要时使您的线程工作

Your command object can contain a "sync" object, so the sender can wait on this object and the processor thread can signal when it has finished. 您的命令对象可以包含“sync”对象,因此发送方可以等待此对象,处理器线程可以在完成时发出信号。 The sync object only needs a boolean and a QWaitcondition, which shouldn't be global. 同步对象只需要一个布尔值和一个QWaitcondition,它不应该是全局的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM