QThread 中的工作者

Worker in QThread

我在 QThread 中有一个工作对象 运行 一些东西在无限循环中。 我在某处看到一个代码,在工作人员中有例如 'checkStatus()' 方法返回一些布尔值。此方法不是插槽而是 public 方法。我感兴趣的是,如果这个 worker 对象已经移入 QThread 并且 运行 是它的无限循环,那么从主线程调用这个方法是否安全?我不应该改用信号槽吗?

我在 main window 的构造函数中尝试了类似的东西:

....
startDataInputSlot(); // starting thread and moving worker into thread

while(1) dataInputWorker->checkStoppedStatus(); // trying to access some variables in worker object

....

startDataInputSlot() 启动了一个线程并将工作线程移入该线程。在 worker 的无限循环中,它会定期检查下一个无限循环(在 main window 中)尝试访问的值。没有使用 QMutex,程序可以正常运行而不会崩溃。使用安全吗?

在没有互斥体的情况下直接访问 worker 成员是不安全的。 这是如何实施的示例:

class Worker : public QObject
{
public slots:
    void doHeavyJob()

public:
    bool getStatus();

private:
    int data;
    QMutex mutex;
}

doHeavyJob 是修改 data 变量的主要工作函数。它应该通过信号槽机制启动,因为在这种情况下它将在工作线程中 运行:

void Worker::doHeavyJob()
{
    while (true)
    {
         mutex.lock();

         // do something with the data
         data++;

         mutex.unlock();
    }
}

QThread *thread = new QThread;
Worker *worker = new Worker;
worker->moveToThread(thread);

connect(thread, SIGNAL(started()), worker, SLOT(doHeavyJob()));

thread->start();

在这里您可以直接从另一个(主)线程检查工作人员状态:

bool Worker::getStatus()
{
    bool isGood;

    mutex.lock();
    isGood = data > 10;
    mutex.unlock();

    return isGood;
}

getStatus 内,您应该锁定 data 变量,因为它可以在 doHeavyJob 槽内更改,即工作线程中的 运行。

你也不能启动getStatus函数作为槽,因为它只会在控制returns到工作线程事件循环时执行,但如果你有'infinite' doHeavyJob函数,永远不会发生。