简体   繁体   中英

how to properly destory a thread pool in c++

So I am using a variable

std::vector<pthread_t> preallocatedThreadsPool;

to hold all the pthreads, then I use a for loop

preallocatedThreadsPool.resize(preallocatThreadsNumber); // create a threadpoOl
for(pthread_t i : preallocatedThreadsPool) {
    pthread_create(&i, NULL, threadFunctionUsedByThreadsPool, NULL);
}

to create the threads pool,

the question is how do I really destory it, for example, when i send signal to the program then i need to manual handle the program to stop all the preallocated pthreads?

I have tried to use another for loop and inside the for loop to call pthread_exit(i) , but the IDE, tell me the for loop will only execute once, which obviously not working

I have tried to use preallocatedThreadsPool.clear(), to clean the vector, however when i use gdb tool to debug it, inside the info threads, the threads are still there?

is there a good way to destory all the preallocated pthreads in my case?

Threads have to exit themselves. You can't exit another thread.

You can use pthread_join to wait for a thread to exit, or pthread_detach to say that you're never going to call pthread_join . You have to call one of these, or it leaks the thread. pthread_join destroys the thread; pthread_detach doesn't destroy the thread (obviously) but it allows the thread to destroy itself when it exits.

Since this is a thread pool, you must have a queue of things you want the threads in the pool to do. You can add special "please exit" items to the end of the queue (or the beginning), and then wait for the threads to exit. Make it so the threads exit when they see a "please exit" item in the queue.

It's all about thread synchronization. The proper way is that you have to have a global flag (a condition variable or a Win32 Event for example) that threads must periodically check and if set, terminate. When a thread is exiting, you must also wait for it to do so, so each thread should signal another event when "I'm done".

After that, any "handle" allocated to pthread or to std::thread or to CreateThread can be destroyed. In std::thread, you can detach and forget about the handle.

Even if you can kill the thread immediately by a function such as TerminateThread (there should be something similar in pthreads), this is very bad, for you will have leaked memory, possibly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM