【问题标题】:std::thread with Qt带有 Qt 的 std::thread
【发布时间】:2020-03-29 18:38:42
【问题描述】:

作为一个学习示例,我正在尝试使用 Qt 而不是 QThreads 来测试 std::thread。该应用程序是一个非常基本的 QMainWindow 应用程序,代码如下:

ma​​inwindow.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

ma​​inwindow.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++;
    }
}

ma​​in.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


【解决方案1】:

不要将指针传递给线程构造函数,而是像这样传递std::reference_wrapper

std::thread t(std::ref(mainWindow));

该包装器来自 &lt;functional&gt; 标头。

您尝试传递引用(按地址)是正确的,因为如果没有,则将创建 MainWindow 的副本(不是您想要的)。但是std::thread 中没有有效的构造函数可以获取指向函子的指针并调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 2017-09-07
    相关资源
    最近更新 更多