首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >线程终止条件

线程终止条件
EN

Stack Overflow用户
提问于 2013-02-26 09:50:07
回答 1查看 184关注 0票数 0

我正在用C语言编写一个生产者-消费者线程程序,我的程序中的所有东西都工作得很好,只有一个主要的例外。当我有多个消费者线程时,实际上只有第一个消费者线程会终止。我已经尝试了我能想到的所有方法,但问题仍然存在。这是我的代码,去掉了它的主要部分,这样你就可以看到相关的部分。

我可以从我的输出中看到两个终止条件变量都变为零,这当然是第一个使用者线程终止的原因。但是为什么其他消费者线程不也终止呢?

谢谢!

代码语言:javascript
复制
sem_t full, empty, mutex;
int threads;
int to_consume;
FILE* inputfp[5];
FILE* outputfp = NULL;
char in[BUF];

void* p(void* inpFile) {

    while (fscanf(inpFile, FMTSTRING, in) > 0) {
        sem_wait(&empty);
        sem_wait(&mutex);
        // production code here
        to_consume++;
        sem_post(&mutex);
        sem_post(&full);
     }

    fclose (inpFile);

    sem_wait(&mutex);
    threads--;
    sem_post(&mutex);

    return NULL;
}

void* c() {

    int continuing = 1;

    while (continuing) {

        sem_wait(&full);
        sem_wait(&mutex);
        //consumption code here
        to_consume--;
        fprintf("%d %d\n", threads, to_consume); //these both go to zero by the end

        if ( (threads <= 0) && (to_consume <= 0) ) {
            continuing = 0;
        }

        sem_post(&mutex);
        sem_post(&empty);
    }

    return NULL;
}

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

    int i;
    int con_threads;
    con_threads = 3;
    to_consume = 0;

    pthread_t *pr_thread[argc-2];
    pthread_t *con_thread[2];

    sem_init(&full, 0, 0);
    sem_init(&empty, 0, 50);
    sem_init(&mutex, 0, 1);

    for (i = 0; i < (argc-2); i++) {
        pr_thread[i] = (pthread_t *) malloc(sizeof(pthread_t)); 
        inputfp[i] = fopen(argv[i+1], "r");
        int rc = pthread_create (pr_thread[i], NULL, p, inputfp[i]);
        sem_wait(&mutex);
        threads++;
        sem_post(&mutex);
    }

    outputfp = fopen(argv[(argc-1)], "wb");

    for (i = 0; i con_threads 3; i++) {
        con_thread[i] = (pthread_t *) malloc(sizeof(pthread_t));
        int rc = pthread_create (con_thread[i], NULL, c, NULL);
    }

    for (i = 0; i < (argc - 2); i++) {
        pthread_join(*pr_thread[i], 0);
        free(pr_thread[i]);
    }

    for (i = 0; i con_threads 3; i++) {
        fprintf(stderr, "About to close consumer thread %d.\n", i);
        pthread_join(*res_thread[i], 0);
        fprintf(stderr, "Consumer thread %d closed successfully.\n", i);
        free(res_thread[i]);
    }

    printf ("About to close the output file.\n");
    /* Close the output file */
    fclose (outputfp);

    return EXIT_SUCCESS;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-26 09:58:44

我认为你的问题是,当第一个消费者检测到没有剩余的线程时,你不会再次发布full,所以第二个消费者正在等待full,但信号永远不会到达。你可能需要一个消费者的计数,但是对于第一次通过(概念证明),你可以给full留下一个永远不会被阅读的帖子。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15079991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档