#include <QThread>
#include <QDebug>
class LambdaRunnable : public QObject
{
Q_OBJECT
public:
explicit LambdaRunnable(std::function<void()> func)
: m_func(func)
{}
~LambdaRunnable()
{
if (m_thread && m_thread->isRunning()) {
m_thread->quit();
m_thread->wait();
delete m_thread;
}
}
public slots:
void run()
{
m_func();
}
void start()
{
if (!m_thread) {
m_thread = new QThread(this);
connect(m_thread, &QThread::started, this, &LambdaRunnable::run);
connect(m_thread, &QThread::finished, m_thread, &QThread::deleteLater);
m_thread->start();
}
}
private:
std::function<void()> m_func;
QThread *m_thread = nullptr;
};
int main()
{
LambdaRunnable *runner = new LambdaRunnable([](){
qInfo() << "Hello from lambda in another thread";
});
runner->start();
// 主线程继续执行其他任务...
// 当你需要停止线程时,可以删除LambdaRunnable对象
// 它的析构函数会确保线程安全地停止
delete runner;
return 0;
}
12-05
4435
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-08
6548
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)