C线程 - 同步

时间:2014-04-17 16:35:56

标签: c multithreading synchronization pthreads

我有这个代码,我正在尝试创建n个线程,在每个线程中做一些工作,然后收获每个线程。如果n thread是偶数,则使用detach,如果是odd,则使用join,

当我运行程序时,它首先打印出Successfully reaped thread,然后正常工作,然后成功收到线程......看起来我有一些同步问题

我甚至需要使用Mutex吗? 任何人都可以帮助我以正确的顺序运行一切吗?

谢谢

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

pthread_mutex_t lock;

void *dowork(){
    //Do whatever needs to be done in each thread here
    pthread_mutex_lock(&lock);
    long tid = (long) pthread_self();
    printf("Doing Work ...for %ld\n",tid);
    pthread_mutex_unlock(&lock);

    //pthread_exit(NULL);
    return;
}

void spawn(int n){
     if (pthread_mutex_init(&lock, NULL) != 0)
    {
        printf("\n mutex init failed\n");
        exit (1);
    }
    int i=0;
    //pthread_t * thread = malloc(sizeof(pthread_t)*n);
    pthread_t threads[n];
     while (i<n) {
        if(pthread_create(&(threads[i]), NULL, dowork, NULL) != 0){
            printf ("Create pthread error!\n");
            exit (1);
        }
        i++;
    }//End of while

    // Wait for threads to complete //
    i = 0;
    while (i<n) 
    {
        int success = -1;

        if(i%2 == 0){
            success=pthread_detach(threads[i]);
        }
        else{
            success=pthread_join(threads[i], NULL);
            }
        if(success==0)
            printf("Succesfully reaped thread\n");
        i++;
    }
      pthread_mutex_destroy(&lock);

}


int main() {
    spawn(5);
}

0 个答案:

没有答案