C程序卡住了,没有进入main()

问题描述 投票:0回答:2

我正在尝试运行一个程序,其中一个线程从标准输入获取数据而另一个线程在标准输出上提供数据,没有太复杂,但是当我用/.filename <test.in> test.out运行我的程序时什么都不做。当我使用gcc -pthread filename.c -o filename -W -Wall对它进行编译时,似乎没有任何错误或警告。谁能解释一下?同样在文件test.out中没有显示任何内容,在test.in中是一个简单的句子。这是该计划

#define V  300

pthread_cond_t cond;
pthread_mutex_t mutex;
char a[300];
int p = 0;
int w = 0;


void *thread1() {

    while(1){
        pthread_mutex_lock(&mutex);
        printf("thread1");
        while(p >0){
            pthread_cond_wait(&cond, &mutex);
        }

        p = fread(a, sizeof(char), V ,stdin);

        if(p == 0){
            pthread_exit(NULL);
        }
        if(p <= V){ 
            pthread_cond_signal(&cond);
        }
        pthread_mutex_unlock(&mutex);
    }

}

void *thread2() {
    while(1){
        pthread_mutex_lock(&mutex);
        printf("thread2");

        while(w >0){
            pthread_cond_wait(&cond, &mutex);
        }

        w = fwrite(a, sizeof(char),p, stdout);

        if(w == 0){
            pthread_exit(NULL);
        }
        if(w <= V ){ 
            pthread_cond_signal(&cond);
        }
        pthread_mutex_unlock(&mutex);
    }
}

int main (void) {
    printf("main/n");
    fflush(stdout);
    pthread_t t1, t2; 

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init (&cond, NULL);

    pthread_create(&t1, NULL, vlakno1,  NULL);
    pthread_create(&t2, NULL, vlakno2,  NULL);


    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}
c multithreading main no-response
2个回答
2
投票

你在printf("main/n");而不是printf("main\n");(或者只是puts("main");)中有明显的错字,但这是一个细节,而不是你的程序永远不会完成的原因

在vlakno1中,你创建了一个死锁:

    if(poc_precitanych == 0){
        pthread_exit(NULL);
    }

因为你没有解锁mutext,一定是

    if(poc_precitanych == 0){
        pthread_mutex_unlock(&mutex);
        pthread_exit(NULL);
    }

你在vlakno2中遇到同样的问题:

    if(pocet_pisanych == 0){
        pthread_exit(NULL);
    }

一定是

    if(pocet_pisanych == 0){
        pthread_mutex_unlock(&mutex);
        pthread_exit(NULL);
    }

以下也很奇怪:

    pocet_pisanych = fwrite(a, sizeof(char),poc_precitanych, stdout);

    if(pocet_pisanych == 0){
        pthread_exit(NULL);
    }

即使这不是不可能的,也很难在没有成功的情况下写入stdout。因此,单独出现这个循环的机会就是让qazxsw poi估值为0

补充说,你poc_precitanych,但你在其他地方使用V时做#define V 300。更好地做char a[300];或在其他地方使用char a[V];而不定义V.


更改后的执行示例:

sizeof(a)

没有什么可读的,所以/tmp % ./a.out < /dev/null main vlakno 1vlakno 2 值为0,两个线程结束,但是

poc_precitanych

0
投票

由于/tmp % echo "1 2 3" | ./a.out main vlakno 1vlakno 1vlakno 21 2 3 ^C 的拼写错误,你在终端上看不到任何东西

printf("main/n");的输出没有刷新到printf,并且创建的线程永远消耗循环,或者至少很长一段时间。

您应该在stdout语句后添加fflush(stdout);来验证这一点。

然后你可以在没有printf的情况下尝试printf("main\n");来验证fflush()是行缓冲的,即:当输出换行符时输出被刷新到终端。

如果将输出重定向到文件,stdout通常是完全缓冲的,因此您应该在每次输出操作后添加一个显式的stdout,这样您就可以动态地或在杀死程序后看到输出文件中的输出。

请注意,如果您使用英语单词作为标识符,类型,注释和消息,则此处的代码将更易于阅读。

© www.soinside.com 2019 - 2024. All rights reserved.