-1

How to create threads only when previous threads are finished?

main {
    create thread1 & thread2

    wait for thread1 & thread2 to finish
    create thread3 & thread4
}
JR Galia
  • 17,229
  • 19
  • 92
  • 144

2 Answers2

1

To wait for a thread to finish, use pthread_join().

In this case though, you're probably better off just leaving thread1 and thread2 running, and have them do the work of thread3 and thread4 respectively once they have finished doing the initial phase of work. You can use pthread_barrier_wait() to ensure that neither proceeds to the second phase of work until both have finished the first phase.

This is a better approach, because creating and exiting threads typically has considerable overhead.

caf
  • 233,326
  • 40
  • 323
  • 462
0

Well, you can use pthread_join. Here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html it is well documented, with an example. I have very little experience with threads, but I've modified it a bit and I think it will work well for your case.

#include <stdio.h>
#include <pthread.h>

typedef struct {
    int *ar;
    long n;
} subarray;


void *incer(void *arg)
{
    long i;
    for (i = 0; i < ((subarray *)arg)->n; i++)
       ((subarray *)arg)->ar[i]++;
}

int main(){

int        ar[1000000];
pthread_t  th1, th2, th3, th4;
subarray   sb1, sb2;


sb1.ar = &ar[0];
sb1.n  = 500000;
(void) pthread_create(&th1, NULL, incer, &sb1);

sb2.ar = &ar[500000];
sb2.n  = 500000;
(void) pthread_create(&th2, NULL, incer, &sb2);

if(pthread_join(th1, NULL)==0 && pthread_join(th2, NULL)==0){
    printf("Creating new threads...\n");
    (void) pthread_create(&th3, NULL, incer, &sb1);
    (void) pthread_create(&th4, NULL, incer, &sb2);
}

return 0;
}
Arkoudinos
  • 1,099
  • 12
  • 20