Reputation: 2135
I have a process with 2 threads. if one of the 2 threads is done executing his instructions, then the other should stop too. And the process should end. How to check if one of the threads has done executing the instructions? This is the code that i have written so far.
#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;
}
Upvotes: 0
Views: 149
Reputation: 409414
First of all you might want to read the pthread_cancel
manual page (and the manual pages for the associated pthread_setcancelstate
and pthread_setcanceltype
functions). The first link contains a nice example.
Another solution is to have e.g. a set of global variables that the threads checks from time to time to see if they should exit or if another thread have exited.
The problem with using e.g. pthread_cancel
is that the thread is terminated without letting you clean up after your self easily, which can lead to resource leaks. Read about pthread_key_create
about one way to overcome this.
Upvotes: 0
Reputation: 145
You can declare a global flag variable and set it to false initially. Whenever a thread reaches its last statement it sets the flag to true. And whenever a thread starts executing it will first check the flag value, if it false i.e. no other thread has updated it continues execution else returns from the function
Upvotes: 1