0

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.

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.

MatiiFine
  • 3
  • 3
  • Unrelated: Try to stay away from using `new` / `delete`. There are usually better options, like smart pointers or no pointers at all. – Ted Lyngmo Apr 25 '22 at 16:33

1 Answers1

1

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);
}
user18533375
  • 175
  • 1