Open nandorsieben opened 1 year ago
in the destructer:
inline ThreadPool::~ThreadPool()
{
{
std::unique_lock
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.
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; }