Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C线程-同步_C_Multithreading_Synchronization_Pthreads - Fatal编程技术网

C线程-同步

C线程-同步,c,multithreading,synchronization,pthreads,C,Multithreading,Synchronization,Pthreads,我有这段代码,我试图创建n个线程,在每个线程中做一些工作,然后收获每个线程。如果n螺纹为偶数,则使用“分离”,如果为奇数,则使用“连接” 当我运行程序时,它首先打印出成功收割的线程,然后进行工作,然后成功收割线程。。。看起来我有一些同步问题 我甚至需要使用互斥吗? 有谁能帮我把一切都安排得井井有条吗 多谢各位 #include <stdio.h> #include <stdlib.h> #include <pthread.h> pthread_mutex_t

我有这段代码,我试图创建n个线程,在每个线程中做一些工作,然后收获每个线程。如果n螺纹为偶数,则使用“分离”,如果为奇数,则使用“连接”

当我运行程序时,它首先打印出成功收割的线程,然后进行工作,然后成功收割线程。。。看起来我有一些同步问题

我甚至需要使用互斥吗? 有谁能帮我把一切都安排得井井有条吗

多谢各位

#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);
}

我还没有尝试运行您的代码,但是分离线程可能会在线程运行时发生-因此您对pthread_detach的调用将立即返回,因此,您成功获取的线程也很可能会在线程有机会打印其正在做的工作之前显示出来。pthread_join将等待线程完成。您需要一个屏障好友。