我试着记住线程是如何工作的,我看到使用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);参数是错误的。
你能解释一下它的工作原理吗?
谢谢。
发布于 2014-06-26 07:25:18
您使用std::cout,所以我假设在thread之前不存在using namespace std;之类的东西。试试std::thread。
试试兰达std::thread t1([this](){this->lancerServeur();});
在退出构造函数之前,不要忘记th1.join(),否则std::terminate将在thread析构函数中被调用。
如果th1中的线程将运行一段时间,那么将其设置为类成员变量,然后初始化将类似于类析构函数th1.join();中的th1 = std::move(std::thread t1([this](){this->lancerServeur();}));。
https://stackoverflow.com/questions/24424645
复制相似问题