我有一个有 2 个线程的进程。如果两个线程之一完成了他的指令,那么另一个也应该停止。这个过程应该结束。如何检查其中一个线程是否已完成执行指令?这是我到目前为止编写的代码。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int read = 0;
int timeLeft = 0;
void *readFromFile(void *myFile){
char *theFile;
theFile = (char*) myFile;
char question[100];
char answer[100];
FILE *file = fopen(theFile, "r");
if(file != NULL){
while(fgets(question,sizeof question,file) != NULL){
fputs(question, stdout);
scanf("%s", &answer);
}
read = 1;
fclose(file);
printf("Done with questions!\n");
pthread_exit(
}
else{
perror(theFile);
}
}
void displayTimeLeft(void *arg){
int *time;
time = (int*) arg;
int i;
for(i = time; i >= 0; i -= 60){
if( i / 60 != 0){
printf("You have %d %s left.\n", i/60,(i/60>1)?"minutes":"minute");
sleep(60);
}
else{
timeLeft = 1;
printf("The time is over \n");
break;
}
}
}
int main(){
pthread_t thread1;
pthread_t thread2;
char *file = "/home/osystems01/laura/test";
int *time = 180;
int ret1;
int ret2;
ret1 = pthread_create(&thread1, NULL, readFromFile,&file);
ret2 = pthread_create(&thread2, NULL, displayTimeLeft,&time);
printf("Main function after pthread_create");
while(1){
//pthread_join(thread1,NULL);
//pthread_join(thread2,NULL);
if(read == 1){
pthread_cancel(thread2);
pthread_cancel(thread1);
break;
}
else if(timeLeft == 0){
pthread_cancel(thread1);
pthread_cancel(thread2);
break;
}
}
printf("After the while loop!\n");
return 0;
}