Qt阻塞线程直到满足条件

时间:2015-06-18 08:49:28

标签: multithreading qt

class Driver : Public QObject
{
    Q_OBJECT

private:
    // method command: sends a command
    // signal ok: command executed, sends back a message
    MyDevice *device;


public:

    Deriver()
    {
        device = new MyDevice(0);
        connect (mydevice,&MyDevice::ok,this,&Driver::onInitOk);
    }

public slots:   
    void init()
    {
        device->command("init");
        //at this point, I want to block this method until the device signals ok with a given msg
    }

    command()
    {
        device->command("setmode x");
        device->command("cmd");
        //at this point, I want to block this method until the device signals ok with a given msg   
    }

    void onInitOk(QString msg)
    {
        //somehow unblock the actually running command, if the msg matches
    }   

}

我想将命令/ init与QueuedConnection一起使用,因此它们从gui线程执行异步,并按顺序执行。 (我是对的吗?)

如何有效实施阻止?

1 个答案:

答案 0 :(得分:0)

好的,所以我根据给出的评论的清晰度进行了编辑。最好看的地方是Qt Threading Guide。这可以更好地分解用于并发的系统。

对于您的示例,我已向您的Driver类添加了QMutex对象。如果您有权访问,可能需要考虑是否要将基于线程的控件移动到MyDevice类中。

Driver()
{
     moveToThread(new QThread());
     device = new MyDevice(0);
}

void init()
{
    mutex.lock(); 
    const QString& result = device->command("init");
    onInitOk(result);
}

void command()
{
    mutex.lock();
    device->command("setmode x");
    const QString& result = device->command("cmd");
    onInitOk(result);
}

void onInitOk(QString msg)
{
  ...[STUFF]
  // Even when things go wrong you MUST unlock the mutex at some point.
  // You can't keep the thread blocked forever in cases of poor results.
  // As such it might be better practice to unlock in
  // the same function that locks!
  mutex.unlock();
}

QMutex mutex;  

请记住我假设您想要从插槽机制访问功能。因此我们使用moveToThead()函数的原因。当通过GUI线程中的插槽访问对象时,它现在将在另一个线程上运行该函数。

同样,互斥锁仅阻止共享该互斥锁实例的所有对象。因此,根据您的实现,您可能需要考虑在暴露该互斥锁时适合您的内容。