Evans Belloeil
Evans Belloeil

Reputation: 2503

Simple error with the creation of a thread

I try to remember of how threads work, I see that with C++11 it simplify the creation and utilisation of it. I use the answer to this post Simple example of threading in C++ for just create a simple thread.

But there's difference between me and the answer of the post, I'm not in a main, so I create my thread in a constructor, and it's not the same parameters.

Here's my simple code and what I try to do:

I'm in a class 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";
}

The errors are :

expected ';' before 't1'

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

I think my parameters for thread t1(lancerServeur, NULL); are false.

Could you explain me how it works ?

Thanks.

Upvotes: 0

Views: 278

Answers (1)

Niall
Niall

Reputation: 30624

You use std::cout, so I'm assuming that the is no using namespace std; or the like somewhere before the thread. Try std::thread.

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

Don't forget to th1.join() before exiting the constructor, else std::terminate will be called in the thread destructor.

If the thread in th1 will run for a while, then make it a class member variable and then the initialisation will look like th1 = std::move(std::thread t1([this](){this->lancerServeur();})); In the class destructor, th1.join();

Upvotes: 4

Related Questions