'Terminating a particular thread on specific condition
I have a program, where there are multiple threads running in an infinite loop. Each thread can handling a certain number of tasks say MAXTASKFOREACHTHREAD. A new thread is generated when the number of tasks increases. If MAXTASKFOREACHTHREAD is not reached, new task will be added into it. But if the task is completed such that number of task in a thread = 0, at a particular point. I want to terminate that thread. I don't want that thread to keep waiting for a task. A new thread can be spawned as needed.
class ThreadPool
{
void createThread();
static void threadFunc(ThreadPool *);
private:
thread t;
int val = 0;
}
void ThreadPool::createThread()
{
t = thread(threadFunc, this);
}
void ThreadPool::threadFunc();
//carries the function implementation regarding tasks
int main()
{
vector<ThreadPool *> v;
v.push_back(new ThreadPool());
v.push_back(new ThreadPool());
v.push_back(new ThreadPool());
v[0].createThread();
v[1].createThread();
v[2].createThread();
}
// Code might have syntax error, I just typed out!
// Now how should I proceed with the deletion of thread, without causing memory corruption!, I need to delete the corresponing object, of the thread
// I am looking for a idea, how to deal with this, without increasing the complexity by using locks.
Please give some suggestions! If any part is not clear that add in comments.
Solution 1:[1]
It seems that you're forgetting that threads run code. You can simply use the worker thread itself to check if there's more work.
First, let's clear up some confusion. A ThreadPool holds multiple threads. In your case, v would be that pool. std::vector is not really a convenient interface for that. So, rename your existing ThreadPool to WorkerThread, and create a ThreadPool with a private: std::vector<WorkerThread>. (objects, not pointers)
The WorkerThread cooperates with ThreadPool. Your WorkerThread::threadFunc has a main loop that checks if there is work. If so, it's executed. But if there's no work, that's the case where you retire the thread. You exit the thread main loop, tell the ThreadPool you're done, and let it call join. Alternatively, detach the WorkerThreads.
Another way to remove threads is to make a special task in the ThreadPool, which causes the WorkerThread which picks it up to exit its main loop. This could be implemented as an empty std::function<>, for instance. In this way, you can actively reduce the number of threads, even if there is work left.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MSalters |
