Pthread_join on two infinite loop threads?

I just read here that when the main loop ends, any threads with or without a chance to spawn cease. Therefore, I need to make a connection in each thread in order to wait for it to return.

My problem is how do I write a program in which I create 2 threads that work in an infinite loop? If I wait to join an endless stream, the second will never get a chance to be created!

+4
source share
2 answers

Two of the main uses of pthread_join : (1) a convenient way to block until a thread is created; (2) you are really interested in the result obtained from the created thread in pthread_join .

If you no longer have work and you just block to prevent the entire process from ending, you can exit main with pthread_exit . Main will exit, but spawned threads will continue.

If you are still not interested in return code, you can create threads just as easily as detached and pthread_exit main.

Having an β€œinfinite” loop in created threads is not best practice. Typically, you want to allow the thread to close. Inside a thread, it can be an eof condition, a closed socket, or whatever. Usually you want to allow the thread to automatically close itself from one or more other external threads. Checking for an infinite loop and similar methods is the easiest way to accomplish this. Otherwise, you need to go through the pthread_cancel route, catch the signals, etc. Everything is a bit more complicated.

+2
source

You can do this with this sequence:

 pthread_create thread1 pthread_create thread2 pthread_join thread1 pthread_join thread2 

In other words, start all your threads before trying to join any of them. In more detail, you can start with something like the following program:

 #include <stdio.h> #include <pthread.h> void *myFunc (void *id) { printf ("thread %p\n", id); return id; } int main (void) { pthread_t tid[3]; int tididx; void *retval; // Try for all threads, accept less. for (tididx = 0; tididx < sizeof(tid) / sizeof(*tid); tididx++) if (pthread_create (&tid[tididx], NULL, &myFunc, &tid[tididx]) != 0) break; // Not starting any is pretty serious. if (tididx == 0) return -1; // Join to all threads that were created. while (tididx > 0) { pthread_join (tid[--tididx], &retval); printf ("main %p\n", retval); } return 0; } 

This will try to start three threads before joining someone, and then join all those with which he managed to switch in the reverse order. The conclusion, as expected, is as follows:

 thread 0x28cce4 thread 0x28cce8 thread 0x28ccec main 0x28ccec main 0x28cce8 main 0x28cce4 
+6
source

All Articles