I have a C++ app in which I create pthreads to run user provided functions. I want to be able to be alerted in some way when a thread exits so that I can remove it from an array of pthread that I am using to keep the threads. Is there a way to do this, or should the function just set some "magic value". Because my main code that spawns the pthreads is in a sort of runloop, I can easily check for an exit condition.
Also, is using a std::vector<pthread_t>
overdoing to keep track of my threads an overload? The number of threads is not necessarily any sort of constant, many threads or very few could be running. Or is there another STL container that would be good for these additions and deletions (additions always at one end, deletions almost anywhere). Is there some other structure for keeping track of pthreads? Would a stack or a list be right here? Or a standard C array with a generous maximum good? Due to the nature of the problem, I could also maintain a fixed size array of worker threads to whom I pass the user functions that must be executed. Is this a good solution?
Sorry for the long confused question, but I have only worked with threading in dynamic languages where this would never be an issue.
EDIT (3/08/12):
After reading @jojojapan's answer, I have decided to use a threadpool of sorts. In my structure, I have one producer (a thread in a runloop) and many consumers (the worker threads in the pool). Is there a data structure that is made for multithreaded one-producer many-consumer use? Or whould I just use a std::queue
with a pthread_mutex_t
on it?