c++ - 使用 Qt 的同步信号

标签 c++ visual-studio-2010 qt

我有两个时间计算相同的函数。第一个需要大约 2 秒来显示结果。第二个也是一样。

但是当我显示不同的结果时,它需要时间计算的总和并使结果在 4 秒内(而不是每个 2 秒)并行显示(对于两个函数)

QTimer* timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(capture()));
connect(timer, SIGNAL(timeout()), this, SLOT(capture_2()));
timer->start(0);

我怎样才能建立一个调用以使其在每个 2 秒内完成?

最佳答案

我会创建几个新 worker ,将他们链接到 QThreads并将您的信号连接到每个 worker 的插槽。诀窍是将标志 Qt::QueuedConnection 传递给连接,因此在两个线程上同时进行调用。别担心,这不会产生两秒钟的开销。

class Worker1 : public QObject
{
Q_OBJECT;
public slots:
    void capture(void);
}

class Worker2 : public QObject
{
Q_OBJECT;
public slots:
    void capture(void);
}


void setup( void )
{
Worker1 * w1 = new Worker1;
Worker2 * w2 = new Worker2;

QThread * t1 = new QThread( w1 );
QThread * t2 = new QThread( w2 );

w1->moveToThread( t1 );
w2->moveToThread( t2 );

t1->start();
t2->start();

QTimer* timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), w1, SLOT(capture()), Qt::QueuedConnection );
connect(timer, SIGNAL(timeout()), w2, SLOT(capture()), Qt::QueuedConnection );
timer->start(0);
}

免责声明:我当场编造了这段代码,它可能需要一些润色,但我希望你明白我的意思。

关于c++ - 使用 Qt 的同步信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16899813/

相关文章:

c++ - 引用传递行为及其范围

visual-studio-2010 - 调试在64位计算机上捕获的32位进程的转储

.net - Teamcity 未满足要求 : MSBuildTools12. 0_x86_Path 存在

python - Qt 现在在 LGPL 下发布,你会推荐它而不是 wxWidgets 吗?

macos - 在 macbook pro 上安装 PYQT5 后如何打开 QT Designer?

c++ - 使用时如何传递参数::AfxBeginThread(ThreadFunc, &INDEX);

c++ - 如何使用 C++ 创建经典的 GUI

c++ - 未解析的外部符号错误,即使函数存在 char*

c# - Azure 无法识别元素 <Target> 下方的元素 <#text>

c++ - 如何使用QT获取计算机的本地IP地址