Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using std::thread outside main source file in c++

I’m trying to use thread but it doesn’t work outside main source file.
For example it doesn’t work

void Game::foo() {
    std::cout << "Why are you not working properly";
}

void Game::threadStart() {
    std::thread th(foo); //here is something wrong
}

But this works(it is in main source file)

void foo() {
    std::cout << "I'm working properly";
}

void thread() {
    std::thread th(foo);
}

What more, when in 2nd option in main file when i want to use pointer on function it doesn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Resource* res = new Resource();
Pocket* pock = new Pocket();

void thread() {
    std::thread th(res->product,pock); // pock is an arg of function product();
}

Any suggestion how to fix it. In the second code I could send pointers as parms and then use

res->product(pock)

but I think using to functions two use 1 thread witch use another function is stupid.

>Solution :

In your Game class example, you are trying to use a class member function as the thread function. This will work, but member functions have the hidden ‘this’ argument.

So you need something like:

void Game::threadStart() {
    std::thread th(&Game::foo, this);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading