【发布时间】:2020-03-29 18:38:42
【问题描述】:
作为一个学习示例,我正在尝试使用 Qt 而不是 QThreads 来测试 std::thread。该应用程序是一个非常基本的 QMainWindow 应用程序,代码如下:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QString>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
[[ noreturn ]] void operator()();
private:
Ui::MainWindow *ui;
QString mm;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include <QDebug>
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
[[ noreturn ]] void MainWindow::operator()()
{
qDebug()<< "thread runing";
int i =0;
while (1)
{
i++;
}
}
main.cpp
#include <thread>
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow mainWindow;
mainWindow.show();
std::thread t(&mainWindow);
t.detach();
return app.exec();
}
此代码无法编译并产生错误:
In file included from /home/faroub/Documents/development-projects/projects-c++/Qt-CMake-GUI/HelloWorld/main.cpp:1:0:
/usr/include/c++/7/thread: In instantiation of ‘struct std::thread::_Invoker<std::tuple<MainWindow*> >’:
/usr/include/c++/7/thread:127:22: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = MainWindow*; _Args = {}]’
/home/faroub/Documents/development-projects/projects-c++/Qt-CMake-GUI/HelloWorld/main.cpp:10:30: required from here
/usr/include/c++/7/thread:240:2: error: no matching function for call to ‘std::thread::_Invoker<std::tuple<MainWindow*> >::_M_invoke(std::thread::_Invoker<std::tuple<MainWindow*> >::_Indices)’
operator()()
^~~~~~~~
任何想法为什么它不起作用?我必须使用 Qt 进行 QThreads 吗?它与QObject有关吗?提前谢谢你。
【问题讨论】:
-
您对 std::thread 到底有什么期望?它的参数必须是可调用的。 Qt 框架和标准线程组件本质上是不兼容的,所以是的,你应该使用 qconcurrent\qthread\qthreadpool
-
这能回答你的问题吗? Start thread with member function
-
@faroub 请注意,大多数 Qt 都不是线程安全的,特别是 GUI 的东西必须在主线程中运行。所以要非常小心你在那个成员函数中所做的事情,它是在另一个线程中执行的。将它放在同一个类中,并且可以访问相同的私有类数据,这是自找麻烦(从多个线程访问它时会出错)。
-
请注意,GUI 元素根本不能在非主线程中使用。您可以与自己的变量进行交互,但不能与小部件交互。
-
阅读关于Qt线程和GUI的答案stackoverflow.com/a/60755238/4149835
标签: c++ multithreading qt std