I have something like a list of things to calculate, and they are somewhat dependent on eachother (some of those calculations, may show that other calculations on the list are not needed).
Also I want to calculate always two of them at a time (two child threads and one main thread (which is a child thread of another one, but that's another story)).
So I want the main thread to wait for ANY of the two treads -the one that finishes first makes the main thread continue-. After it continues, it will run some code to see if the other running thread can be killed (if the one that finished shows that the other is not needed), or not, and also to run a new thread.
The idea is to do something like this:
while (/*list not empty*/) {
/*detect which two entries need to be calculated*/
/*detect if running thread can be killed*/
if (/*running thread can be killed*/) {
pthread_join(/*threadnum*/, NULL)
}
switch (/*how many threads already running?*/) {
case 0:
pthread_create(/*&threadnum*/, NULL, /*calculate*/, /*foo*/);
case 1:
pthread_create(/*&threadnum*/, NULL, /*calculate*/, /*foo*/);
break;
}
/* !!!!!!!!! Question code is next line: !!!!!!!!!*/
pthread_join(/*What goes here?*/, NULL);
// If it is impossible to do with pthread_join, what else can be used?
}
My first approach (if this was impossible) would be to store in an array the status of both threads, and check every second (with a while and sleep(1)) if any of them finished, but that would make me lose time (between 0 and 1 seconds) every time a thread finishes. So I want to avoid that if possible.
EDIT: pthread_cond_wait(/* something */) seems the way to go. However I want it to be easy: the main thread and both child threads share a global variable (parent) that is set to 0 if child threads are running, and is set to 1 when one of them stops. Ideally I want to control from the main thread everything in this way:
while (/*list not empty*/) {
/*detect which two entries need to be calculated*/
/*detect if running thread can be killed*/
if (/*running thread can be killed*/) {
pthread_join(/*threadnum*/, NULL)
}
switch (/*how many threads already running?*/) {
case 0:
pthread_create(/*&threadnum*/, NULL, /*calculate*/, /*foo*/);
case 1:
pthread_create(/*&threadnum*/, NULL, /*calculate*/, /*foo*/);
break;
}
/* !!!!!!!!! Question code is next line: !!!!!!!!!*/
pthread_cond_wait(parent, /*wtf?*/)
}
Now I have an idea to stop the parent until that condition is met, which I can set to 1 inside the child threads.
Instead of making the main thread monitor and try to kill other threads, make the other threads communicate directly amongst themselves.
For example, if thread A finishes and it becomes clear that the computation in thread B is no longer needed, simply set a boolean flag. Make thread B check that flag between steps of its computation, and give up if the flag is set.
Trying to interrupt threads is bad practice--you're better off just setting a flag that the threads will check.