互斥锁 - 使用线程

时间:2017-10-19 15:28:35

标签: c multithreading pthreads mutex

您好我正在编写一个代码,用于计算使用线程在一个或多个文件中出现某个字母的次数。我必须为每个文件使用一个线程e使用互斥锁来修改全局总数。

这是我的代码:

typedef struct _CharFile{

    char c;
    char *fileName;

} CharFile;

pthread_mutex_t count = PTHREAD_MUTEX_INITIALIZER;
int sum = 0;

void *CountFile(void *threadarg);

int main(int argc, const char * argv[]) {

    pthread_t threads[argc-2];
    int chck, t;
    CharFile cf;

    if (argc <= 2){

        perror("Wrong inputs: need to select a letter and one or more files\n");
        exit(EXIT_FAILURE);

    } else if (argc > 51) {

        perror("Too many files\n");
        exit(EXIT_FAILURE);

    }

    for ( t=0 ; t<argc-2 ; t++ ){

        cf.c = argv[1][0];
        cf.fileName = (char *)argv[t + 2];

        chck = pthread_create(&threads[t], NULL, CountFile, (void *) &cf);
        if (chck){
            printf("ERROR; return code from pthread_create() is %d\n", chck);
            exit(EXIT_FAILURE);
        }

    }

    for (int i = 0; i < 2; i++)
        pthread_join(threads[i], NULL);

    printf("%lld occurrences of the letter %c in %lld threads\n", (long long)sum, argv[1][0], (long long)argc-2);

    return 0;
}

void *CountFile(void *threadarg){

    FILE *in;
    CharFile *cf;
    char c;
    int counter = 0;

    cf = (CharFile *) threadarg;
    in = fopen(cf->fileName, "r");

    if (in == NULL){

        perror("Error opening the file!\n");
        pthread_exit(NULL);

    }

    while (fscanf(in, "%c", &c) != EOF){

        if(c == cf->c){

            counter ++;

        }

    }

    fclose(in);

    pthread_mutex_lock(&count);
    sum += counter;
    printf("%d sum value, %d counter value \n", sum, counter);
    pthread_mutex_unlock(&count);

    pthread_exit(NULL);
}

我不知道哪里出错了,但是我使用了一些字母,结果很奇怪。

两次运行此行./a.out f file1.in lorem.txt notes.txt我得到以下结果:

4 sum value, 4 counter value 
9 sum value, 5 counter value 
13 sum value, 4 counter value 
13 occurrences of the letter f in 3 threads

4 sum value, 4 counter value 
8 sum value, 4 counter value 
12 sum value, 4 counter value 
12 occurrences of the letter f in 3 threads

如果我只用一个文件运行一个更简单的命令行,那么计数是正确的,即./a.out f file1.in

5 sum value, 5 counter value 
5 occurrences of the letter f in 1 threads

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

我认为你的问题可能在这里:

for ( t=0 ; t<argc-2 ; t++ ){

    cf.c = argv[1][0];
    cf.fileName = (char *)argv[t + 2];

    chck = pthread_create(&threads[t], NULL, CountFile, (void *) &cf);
    if (chck){
        printf("ERROR; return code from pthread_create() is %d\n", chck);
        exit(EXIT_FAILURE);
    }

}

您向所有线程传递指向同一变量的指针(即cf)。将指针传递给第一个线程后,更改cf的值并将指针传递给第二个线程,所以。

因此,在“刚刚开始”线程读取其值之前,主循环可能会发生变化cf,即线程可能会打开另一个文件而非预期。

通过将cf更改为数组,即每个线程一个元素,确保每个线程都拥有自己的cf