Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to wait for all Tasks to finish? #30

Open
Ravenbs opened this issue Aug 23, 2020 · 2 comments
Open

How to wait for all Tasks to finish? #30

Ravenbs opened this issue Aug 23, 2020 · 2 comments

Comments

@Ravenbs
Copy link

Ravenbs commented Aug 23, 2020

Sorry for writing this as an issue.

I could not figure out how it is ment to wait for all Tasks to finish.
If i use stop - the Threads get deleted and the threadpool ends.

Isn't there something like p.WaitForEverythingDone()?
Currently I use this in the main thread:
while (p.n_idle() < THREAD_COUNT )
{
}
But thats not really a good idea to burn 1 cpu core just for waiting?

@pemsley
Copy link

pemsley commented Aug 23, 2020

Yeah, don't use stop() :-)
This is what I do:
In the main thread, create an atomic int set to 0 (call it thread_count, say). This atomic int is passed to the thread (each thread) as a std::ref() and the thread updates thread_count (adds 1) when it's finished processing, i.e. at the end of the function.
The main thread just waits for the atomic int to match what I expected it to be (10 for 10 threads, say)

    while (thread_count < 10) {
       std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }

This way, somewhere else in the program, using the same thread pool, but (say) doing physics, can keep using threads without interfering.

@Ravenbs
Copy link
Author

Ravenbs commented Aug 24, 2020

Thank you.
But found a better way as bussy waiting/polling or with sleep I want to share:

Make a list of Thread handels:
std::vector<std::future> threadhandles;

Start you tasks:
threadhandles.push_back(p.push(....));

Wait all tasks to finish:
for (int i = 0; i < threadhandles.size(); i++)
threadhandles[i].wait();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants