2014-06-26 33 views
0

我尝试记住线程是如何工作的,我发现使用C++11可以简化它的创建和使用。我使用这个职位Simple example of threading in C++的答案来创建一个简单的线程。创建线程时出现简单错误

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

这里是我的简单的代码和我尝试做:

我在一类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);是错误的。

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

谢谢。

回答

4

您使用std::cout,所以我假设using namespace std;thread之前的某个地方。尝试std::thread

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

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

如果th1线程将运行一段时间,然后使它成为一个类的成员变量,然后初始化看起来像th1 = std::move(std::thread t1([this](){this->lancerServeur();}));在类的析构,th1.join();

+0

,当我在前面使用std我这有线程:没有匹配的函数调用'std :: thread :: thread(,NULL)' –

+0

函数'MainWindow :: lancerServeur'应该是静态的或使用lambda'std :: thread( [this](){this-> lancerServeur();});' – Niall

+0

如果我把它放在静态我有这样的:'class std :: result_of ' typedef typename result_of <_Callable(_Args ...)> :: type result_type; –