c++ - 创建线程的简单错误

标签 c++ multithreading c++11

我试着记住线程是如何工作的,我看到 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/

相关文章:

c++ - 如何包含 GDB 调试符号 'break packages' ?

android - 如何从 ARCore NDK 中的 ArCamera Pose 获取 Matrix4x4?

c++ - 运行具有授予权限的 NPAPI 插件 (firebreath)

c++ - 使用数组对整数进行排序。

c++ - 获取没有对象的成员函数的返回类型

c++ - 使用对 const char * 的右值引用的重载解析

.net - 用于长时间运行任务的线程池或 TPL

javascript - setTimeout 或 setInterval 是否使用线程触发?

c - POSIX 多线程和信号处理

c++ - 公共(public)删除或私有(private)默认构造函数/分配/复制构造函数?