Search code examples
c++multithreadingstdthread

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.

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);
    }