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

testing if pool is empty #104

Open
nandorsieben opened this issue May 17, 2023 · 1 comment
Open

testing if pool is empty #104

nandorsieben opened this issue May 17, 2023 · 1 comment

Comments

@nandorsieben
Copy link

If I make the "tasks" variable public, then the following code for factoring an integer seems to work. Is there a better way to test if there are still tasks to finish?

#include
#include
#include
#include "math.h"

#include "ThreadPool.h"

ThreadPool pool(4);
std::mutex mtx;
std::vector factors;

void split(int x){
int sqt = int (sqrt (double (x)));
for (int y = sqt; y > 1; y--) // search for divisors
if (0 == x % y) { // found a divisor
pool.enqueue(split, x/y); // submit two new jobs
pool.enqueue(split, y);
return;
}
mtx.lock();
factors.push_back(x); // prime factor
mtx.unlock();
}

int main()
{
int x = 1120581000;
pool.enqueue(split, x);
while (!pool.tasks.empty()) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
for (auto f : factors)
std::cout << f << " ";
return 0;
}

@Zzzzzya
Copy link

Zzzzzya commented Oct 31, 2023

in the destructer:
inline ThreadPool::~ThreadPool()
{
{
std::unique_lockstd::mutex lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}

all the worker thread will be joined. So all u need to do is to make sure the main thread will not be end. u can add a getchar() in the main . In fact , I think there should be a public api in the class, maybe called "WaitAllTasksDone",to block the main thread and wait for all tasks in the pool be done but not destroy the pool.

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