-1

仅在先前的线程完成时如何创建线程?

main {
    create thread1 & thread2

    wait for thread1 & thread2 to finish
    create thread3 & thread4
}
4

2 回答 2

1

要等待线程完成,请使用pthread_join().

不过,在这种情况下,您最好让线程 1 和线程 2 运行,并让它们在完成初始阶段的工作后分别执行线程 3 和线程 4 的工作。您可以使用pthread_barrier_wait()以确保在双方都完成第一阶段之前,双方都不会进入第二阶段的工作。

这是一种更好的方法,因为创建和退出线程通常具有相当大的开销。

于 2015-07-22T00:26:52.363 回答
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;
}
于 2015-07-22T00:41:51.310 回答