QT多线程中run()函数与start()的联系

1.run函数结束后,线程结束:QThread是用来控制一个线程的,而不是线程自身。当run()函数结束之后,这个线程就会被终结,但创建的QThread对象仍然存在,且创建的子线程可以循环使用。
2.start()函数可多次调用:QThread只是new出来的一个对象,当调用start()之后,它会新建一个线程,并把run()中的代码放到线程中运行,当运行完成后,线程会结束,但QThread对象还在,所以可再次调用start()函数。

问题:当run函数没有运行完时,再次调用start()会出现什么情况?

  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
Sure, I'd be happy to help you with that question. Here is a simple example of a Qt multi-threaded program that demonstrates how to use callback functions: ``` #include <QtCore/QCoreApplication> #include <QtCore/QThread> class WorkerThread : public QThread { Q_OBJECT public: WorkerThread(QObject* parent = nullptr) : QThread(parent) {} protected: void run() override { // Do some work, and then call the callback function int result = 123; // Call the callback function with the result callback(result); } public: typedef void (*CallbackFunc)(int); void setCallback(CallbackFunc func) { callback = func; } private: CallbackFunc callback; }; void someCallback(int result) { qDebug() << "Callback called with result:" << result; } int main(int argc, char* argv[]) { QCoreApplication app(argc, argv); WorkerThread thread; thread.setCallback(someCallback); thread.start(); return app.exec(); } ``` In this example, we create a WorkerThread class that inherits from QThread. We override the run() method to do some work and then call a callback function. We also define a typedef for the callback function, so we can easily pass it as a parameter to the setCallback() method. In the main() function, we create an instance of the WorkerThread class, set the callback function using the setCallback() method, and start the thread using the start() method. The main() function then enters the Qt event loop using the app.exec() method. When the WorkerThread instance runs, it will do some work and then call the callback function with a result value. The someCallback() function will be called with the result value and print it to the console. I hope this simple example helps you understand how to use callbacks with multi-threaded Qt programs.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w5875895

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值