0

我有一个有 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;

}
4

2 回答 2

1

您可以声明一个全局标志变量并将其最初设置为 false。每当一个线程到达它的最后一条语句时,它就会将该标志设置为真。每当一个线程开始执行时,它会首先检查标志值,如果它为假,即没有其他线程更新,它会继续执行,否则从函数返回

于 2013-11-10T10:13:37.477 回答
0

首先,您可能想阅读pthread_cancel手册页(以及相关功能的手册页pthread_setcancelstatepthread_setcanceltype。第一个链接包含一个很好的例子。

另一种解决方案是拥有一组全局变量,线程不时检查这些变量以查看它们是否应该退出或另一个线程是否已经退出。

使用 eg 的问题pthread_cancel是线程被终止而没有让你轻松地清理自己,这可能导致资源泄漏。阅读有关pthread_key_create克服此问题的一种方法。

于 2013-11-10T10:13:03.577 回答