Есть ли способ присоединиться к указанному потоку c, зная только его идентификатор? - PullRequest
1 голос
/ 15 января 2020

Учитывая конечное число врачей и бесконечное количество пациентов (которые генерируются в случайные моменты (в то время как (1) l oop), мне нужно составить программу, которая описывает планирование. Пока что я создал связанный список, содержащий идентификаторы потоков, которые в данный момент находятся на консультации у какого-то врача, и while (1) l oop прерывается при нажатии CTRL + C. На этом этапе больше не генерируются пациенты, а те которые не завершили свою консультацию, ожидают окончания sh (с помощью pthread_join). Моя проблема сейчас: как мне ждать (pthread_join) тех, кто знает только их идентификаторы из связанного списка?

Для процессов у меня есть waitpid (pid), а для потоков - как мне это преодолеть?

Ниже приведен мой код, если он помогает


#define MAX_CONSULTATION_TIME 15
#define noOfDoctors 4

struct node
{
    struct node *next;
    pid_t pid;
}*head, *tail;

void * need_a_doctor(int *noOfPatient)
{

        arrivalTime[*noOfPatient] = time(NULL);
        if(sem_wait(&sem))
    {
        perror(NULL);
        return errno;
    }
    pid_t myPid = pthread_self();
    printf(" pid: %d " , myPid);
    struct node * n;
    n = add_a_new_patient_thread(myPid);    
    int *indexDoctor;
    indexDoctor = (int *)malloc(sizeof(int));
    block_doctor(indexDoctor);
    time_t currentTime = time(NULL);
    unsigned long long periodBlockDoctor = rand() % (MAX_CONSULTATION_TIME + 1);
    printf("Under consultation doctor %d with patient %d\n", (*indexDoctor) + 1, *noOfPatient);
    sleep(periodBlockDoctor);

    release_doctor(indexDoctor);
    printf("Patient %d with doctor %d waited for %ld seconds and the consultation took %lld seconds\n" , (*noOfPatient) , (*indexDoctor) + 1 , currentTime - arrivalTime[*noOfPatient] , periodBlockDoctor);
    remove_an_existing_patient(n);
    if(sem_post(&sem))
    {
        perror(NULL);
        return errno;
    }

    return NULL;
}
int main(int argc, char ** argv)
{
        head = (struct node *)malloc(sizeof(*head));
        tail = (struct node *)malloc(sizeof(*tail));
        srand(time(NULL));
        for(int i = 0 ; i < 4 ; i++)
            doctorTaken[i] = 0;
        if(argc < 1)
        {
            fprintf(stderr , "Invalid number of arguments\n");
            return -1;
        }


        if(pthread_mutex_init(&mtx , NULL))
        {
            perror(NULL);
            return errno;
        }
        if(sem_init(&sem , 0 , noOfDoctors))
        {
            perror(NULL);
            return errno;
        }

        unsigned long long timeWaitingPatient;

        int index;
        signal(SIGINT , handler_function);

        while(1)
        {

        timeWaitingPatient = rand() % 4;
        sleep(timeWaitingPatient);
        if(myExit == 1){ break;}
        printf("Patient no. %d\n" , k);

        int *index;
        index = (int *)malloc(3 * sizeof(int));

        if(index == NULL)
        {
            fprintf(stderr , "Lack of memory");
            return -1;
        }
        (*index) = k;
        pthread_t t;
        if(pthread_create(&t , NULL , need_a_doctor , index))
        {
            perror(NULL);
            return errno;
        }

            k++;
    }
    /*
    How do I join the remaining threads here?
    */
//  }
    return 0;
}

1 Ответ

2 голосов
/ 15 января 2020

Когда вы создаете pthread с pthread_create, вы передаете pthread_t*, чтобы получить идентификатор потока. Затем вы можете дождаться завершения этого потока, вызвав pthread_join и передав ему идентификатор этого потока.

...