如何在完成它之前的功能后更改pthread的功能

时间:2017-10-26 07:58:53

标签: c multithreading operating-system pthreads

我有walker [0]个进程数。他们必须沿着AB和BC前进。 AB = 100。 in.txt包含进程的速度。我需要将完成AB的第一个进程传递给BC。我怎样才能做到这一点?这是我到目前为止所做的跨越AB。它对我来说很好。但是我想把这个过程发送到BC。 假设10中的进程数及其速度的情况 4 2 4 3 2 2 五 1 3 4

#define AB 100
#define BC 5
void *thread_function(void *arg);
void *thread_function_BC(void *arg);
sem_t bin_sem;


int walker[255];
int distance[255];
int distance_BC[255];
int main() {
    int p;
    for(p=0;p<255;p++)
    {
        distance[p]=0;
        distance_BC[p]=0;
    }

    FILE* fp;
    char buffer[255];

    int i=0,j=1,k=0,l;
    fp = fopen("in.txt", "r");

    while(fgets(buffer, 255, (FILE*) fp)) {
        walker[i]=atoi(buffer);
        i++;
    }
    fclose(fp);
    int res;
    pthread_t a_thread[10];
    pthread_t b_thread[10]; 
    void *thread_result;

    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    for(i=1;i<=walker[0];i++){
        res = pthread_create(&a_thread[i], &attr, thread_function, (void *)i);
        if (res != 0) {
            perror("Thread creation failed");
            exit(EXIT_FAILURE);
        }

    }
    for(i=1;i<=walker[0];i++){
        while(distance[i]<AB);
    }


    for(i=1;i<=10;i++){

        res = pthread_join(a_thread[i], &thread_result);

        if (res != 0) {
            perror("Thread join failed");
            exit(EXIT_FAILURE);
        }
    }   
}
void *thread_function(void *arg) {
    int l,k;    
    int i=(int)arg;
    while(distance[i]<AB){
        if(distance[i]+walker[i]>AB){
            printf("Person %d moved along AB from %d to %d\n",i,distance[i],100);
            distance[i]=100;
        }
        else{
            printf("Person %d moved along AB from %d to %d\n",i,distance[i],distance[i]+walker[i]);
            distance[i]=distance[i]+walker[i];
        }

    }


}

0 个答案:

没有答案