c - C程序卡住,不进入main()
问题描述
我正在尝试运行一个程序,其中一个线程从标准输入中获取数据,然后另一个线程在标准输出上提供数据,没什么太复杂的,但是当我使用/.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;
}
解决方案
您的printf("main/n");
而不是printf("main\n");
(或只是puts("main");
)中有明显的错字,但这是一个细节,而不是您的程序永远不会完成的原因
在vlakno1中,您创建了一个死锁:
if(poc_precitanych == 0){
pthread_exit(NULL);
}
因为你不解锁互斥锁,必须是
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);
}
即使不是不可能,也很难在没有成功的情况下在stdou上进行写入。因此,您退出该循环的唯一机会就是将值设为poc_precitanych
0
补充说明一下,您在其他地方使用V#define V 300
时会这样做。最好在不定义 V的情况下做或在别处使用char a[300];
char a[V];
sizeof(a)
更改后的执行示例:
/tmp % ./a.out < /dev/null
main
vlakno 1vlakno 2
没有什么可读取poc_precitanych
的,所以值为 0 并且两个线程完成,但是
/tmp % echo "1 2 3" | ./a.out
main
vlakno 1vlakno 1vlakno 21 2 3
^C
推荐阅读
- mysql - 等效查询对不同的表抛出错误:语法错误或访问冲突:1055 SELECT 列表的表达式 #2 不在 GROUP BY 中
- flutter - 决定在 Dart/Flutter 中添加 const 的对象层次结构中的哪个级别
- functional-programming - Ocaml 中的表达式
- java - Dagger2 Android 依赖注入 java
- python - Python 函数以最小的可能时间顺序 (O(n)) 在字典中查找所有第二低的 SCORERS
- javascript - 在文本中查找大写字母的问题
- r - R中的子集字符向量
- ruby-on-rails-5 - 如何序列化存储的正确字段有一个 has_many through 关系表
- php - 如何更改laravel中的数组结构?
- python - 当每行是一个列表时,替换不适用于多个字符串替换