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