3

设想

可以说,我有一个名为parallelRun. 它需要一个工人列表,每个工人都有一个getWorkAmount():int,一个run()方法,一个finished()信号和一个cancel()槽:

void parallelRun( std::vector< Worker* > workers );

其实施应:

1.打开一个QPogressDialog

unsigned int totalWorkAmount = 0;
for( auto it = workers.begin(); it != workers.end(); ++it )
{
    totalWorkAmount += ( **it ).getWorkAmount();
}

LoadUI ui( 0, totalWorkAmount, this );

class LoadUI : public QObject
{
    Q_OBJECT

public:

    LoadUI( int min, int max, QWidget* modalParent )
        : totalProgres( 0 )
        , progressDlg( "Working", "Abort", min, max, modalParent )
    {
        connect( &progressDlg, SIGNAL( canceled() ), this, SLOT( cancel() ) );

        progressDlg.setWindowModality( Qt::WindowModal );
        progressDlg.show();
    }

    bool wasCanceled() const
    {
        return progressDlg.wasCanceled();
    }

public slots:

    void progress( int amount )
    {
        totalProgres += amount;

        progressDlg.setValue( totalProgres );
        progressDlg.update();

        QApplication::processEvents();
    }

signals:

    void canceled();

private slots:

    void cancel()
    {
        emit canceled();
    }

private:

    int totalProgres;
    QProgressDialog progressDlg;
}

2.为每个worker创建一个线程

std::vector< std::unique_ptr< QThread > > threads;
for( auto it = workers.begin(); it != workers.end(); ++it )
{
    std::unique_ptr< QThread > thread( new QThread() );

    Worker* const worker = *it;
    worker->moveToThread( thread.get() );

    QObject::connect( worker, SIGNAL( finished() ), thread.get(), SLOT( quit() ) );
    QObject::connect( &ui, SIGNAL( canceled() ), worker, SLOT( cancel() ) );
    QObject::connect( *it, SIGNAL( progressed( int ) ), &ui, SLOT( progress( int ) ) );

    thread->start( priority );

    threads.push_back( std::move( thread ) );
}

3.同时运行它们

for( auto it = workers.begin(); it != workers.end(); ++it )
{
    QMetaObject::invokeMethod( *it, "run", Qt::QueuedConnection );
}

load()当用户单击 UI 按钮时运行。

问题

如果我想parallelRun阻塞直到所有工作人员完成,我应该如何扩展这段代码,而不冻结QProgressDialog

审议

使用屏障

parallelRun我尝试在例程末尾添加以下代码:

QApplication::processEvents();
for( auto it = threads.begin(); it != threads.end(); ++it )
{
    ( **it ).wait();
}

这几行额外代码的影响是,LoadUI::progress永远不会进入,因为 GUI 线程处于休眠状态,因此它的事件循环没有被处理:在 Qt 中,信号通过将它们发布到事件循环来传递到插槽线程,与插槽所属的对象相关联。这就是为什么progressed永远不会传递工人的信号的原因。

我认为,适当的解决方案是在工作人员发出信号时QApplication::processEvents() 在 GUI 线程中运行。progressed另一方面,我想这是不可能的,因为 GUI 线程已经睡着了。

另一种可能的解决方案

另一种可能性是使用类似主动等待的解决方案:

for( auto it = threads.begin(); it != threads.end(); ++it )
{
    while( ( **it ).isRunning() )
    {
        QApplication::processEvents();
    }
}
for( auto it = threads.begin(); it != threads.end(); ++it )
{
    ( **it ).wait();
}

这还需要在之后添加以下代码行thread->start( priority );

while( !thread->isRunning() );

我不认为这是一个很好的解决方案,但至少它有效。如果没有主动等待的缺点,如何做到这一点?

提前致谢!

4

2 回答 2

1

而不是自己构建。也许 QThreadPool 是您正在寻找的?

QThreadPool 有一个等待所有工作线程的功能。

于 2012-07-06T11:00:29.423 回答
1

您可以使用线程的finished()信号来等待它们在主 GUI 循环中完成,而不是使用QApplication::processEvents. 进度对话框模式将确保只有该对话框窗口处于活动状态,直到它被显式关闭。

class WorkerManager : public QObject {
    Q_OBJECT
private:
    // to be able to access the threads and ui, they are defined as a members
    std::vector<std::unique_ptr<QThread> > threads;
    LoadUI *ui;

    int finishedThreadCount;
public:
    WorkerManager() 
        : finishedThreadCount(0)
    {
        // Open the QProgressDialog
        ...
        // Create and start the threads
        ...
        // Connect the finished() signal of each thread 
        // to the slot onThreadFinished
        for( auto it = threads.begin(); it != threads.end(); ++it )  {
            QObject::connect(
                it->get(), SIGNAL(finished()), 
                this, SLOT(onThreadFinished()) );
        }
    }

private slots:
    void onThreadFinished() {
         ++finishedThreadCount;

         if(finishedThreadCount == threads.size()) 
         {
              // clean up the threads if necessary
              // close the dialog
              // and eventually destroy the object this itself
         }
    }
};

或者你可以运行一个嵌套QEventLoop来等待线程同步完成,同时仍然保持 GUI 响应:

// Open the QProgressDialog
...
// Create and start the threads
...
// Create and run a local event loop,
// which will be interrupted each time a thread finishes
QEventLoop loop;
for( auto it = threads.begin(); it != threads.end(); ++it )  
{
    QObject::connect(
        it->get(), SIGNAL(finished()), 
        &loop, SLOT(quit()) );
}  
for(int i = 0, threadCount = threads.size(); i < threadCount; ++i) 
    loop.exec();

如果只有在工作完全完成时进度才达到最大值,您可以使用whichprogressDlg->exec()代替QEventLoopwhich 将阻塞直到达到最大值或直到用户单击“取消”按钮。

于 2012-07-06T12:50:45.557 回答