gpt4 book ai didi

c++ - 重新实现 QThread 的 start()

转载 作者:太空宇宙 更新时间:2023-11-04 14:08:22 24 4
gpt4 key购买 nike

我正在练习 Qt 中的线程。我重新实现了 run()(尽管不推荐这样做)并且一切正常。

现在我想通过让它传递一个变量来向 run() 添加更多功能:run(int i)。此外,我希望调用 run 的 start() 将变量传递给 run(int i):start(int j)


我认为按以下方式重新实现启动应该可行:(Zaehler 是 QThread)

void Zaehler::start(int ZaehlerIndex)
{
运行(ZaehlerIndex),
终止();
}

其实并没有。我的 GUI 在启动线程时卡住。


问题:我知道,应该避免搞乱开始和运行,但有没有办法做到这一点?我做错了什么吗?

备注:我查找了 qthread.cpp 以查看 start() 是如何实现的,但我发现的只是

\sa run(), terminate() 被注释掉了!所以它实际上根本不应该工作!?

最佳答案

这样的事情怎么样?

class Worker
{
//note, only pass parameters by copy here.
public:
Worker(int param) : myParam(param) {}

public slots:
void process()
{
//do something with myParam here, it will run in the thread.
}

signals:
void finished();
void error(QString err);

private:
int myParam;
};

然后可以像这样使用“moveToThread”连接到线程对象:

QThread* thread = new QThread;
Worker* worker = new Worker(5);
worker->moveToThread(thread);
connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
connect(thread, SIGNAL(started()), worker, SLOT(process()));
connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();

有关 Qt 中线程使用的更多信息和简短教程,请参见此处: http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/

关于c++ - 重新实现 QThread 的 start(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15971660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com