我试图记住线程是如何工作的,我发现使用C++11可以简化线程的创建和使用。我使用这篇帖子Simple example of threading in C++的答案只是创建一个简单的线程。

但是我和帖子的答案之间存在差异,我不在主要人员中,所以我在构造函数中创建了线程,并且参数不相同。

这是我的简单代码以及我要尝试执行的操作:

我正在上课mainWindow.cpp

//Constructor
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(lancerServeur, NULL);
    ui->setupUi(this);
}
void MainWindow::lancerServeur(){
    std::cout << "Le serveur se lance";
}


错误是:

expected ';' before 't1'

statement cannot resolve address of overloaded function thread t1(lancerServeur, NULL);


我认为我的thread t1(lancerServeur, NULL);参数是错误的。

您能解释一下它是如何工作的吗?

谢谢。

最佳答案

您使用std::cout,所以我假设using namespace std;之前的某处不是thread或类似内容。尝试std::thread

尝试lambda std::thread t1([this](){this->lancerServeur();});

不要忘记退出构造函数之前先进入th1.join(),否则std::terminate将在thread析构函数中被调用。

如果th1中的线程将运行一段时间,则使其成为类成员变量,然后初始化将类似于th1 = std::move(std::thread t1([this](){this->lancerServeur();}));在类析构函数中,th1.join();

关于c++ - 创建线程时出现简单错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24424645/

10-11 22:49
查看更多