考虑到有限数量的医生和无限数量的患者(它们是在随机时刻生成的(在while(1)循环中),我需要编写一个描述计划的程序。到目前为止,我已经创建了一个链表)包含当前正在某个医生处接受咨询的线程的ID,并且在命中CTRL + C时while(1)循环中断。此时,不再产生更多的患者,而尚未完成咨询的患者为正在等待完成(使用pthread_join)。现在我的问题是:如何仅从链接列表中知道其ID,如何等待(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;
}
[使用pthread_create
创建pthread时,您传入pthread_t*
以接收线程ID。然后,您可以通过调用pthread_join
并将该线程ID传递给它来等待该线程完成。