我使用pthread_cond_wait()和pthread_cond_signal()函数创建了一个多线程程序。如果条件正确,它可以正常工作,但条件不正确,它不工作,它不会忽略函数printinput(),它会留在这里,不会继续运行。你能帮我检查一下这个错误吗?
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
//Read input value
void* readinput(void *arg)
{
pthread_mutex_lock(&mutex);
int a;
printf("Input:");
scanf("%d",&a);
printf("Value: %d\n",a);
/*
if condition correct then "printinput" function
else ignore that function
*/
if (a>=2 && a<=8)
{
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
pthread_exit((void *)a);
}
//print input value if condition correctly
void* printinput(void *arg)
{
pthread_mutex_lock(&mutex);
//Block and wait for cond Singal
pthread_cond_wait(&cond,&mutex);
printf("Your value between 2 and 8 \n\n");
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main()
{
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_t th1;
pthread_t th2;
while (1)
{
//Create pthread
pthread_create(&th1,NULL,&printinput,NULL);
pthread_create(&th2,NULL,&readinput,NULL);
//Wait pthread done
pthread_join(th1,NULL);
pthread_join(th2,NULL);
Sleep(1000);
}
}结果:
Input:5
Value: 5
Your value between 2 and 8
Input:10 Value: 10发布于 2016-10-18 11:52:21
pthread_cond_wait()挂起当前线程,直到发出相关条件的信号。
对于输入5,第一线程发信号通知条件,因为它是if (a >= 2 && a <= 8)块的一部分。
对于输入10,将跳过上面的块,因此永远不会发出信号通知该条件。因此,第二个线程永远不会被唤醒,并且永远被卡住。
此外,请注意有竞争条件,我实际上感到惊讶的是,程序经常工作。在第一个线程锁定互斥锁的情况下,第二个线程直到第一个线程函数完成才进入互斥锁部分,因此在调用对该条件的等待之前会发出该条件的信号。在这种情况下,第二个线程也会永远被卡住。
对于以您期望的方式工作的解决方案(即从第二个线程中的第一个线程消费true/false ),我建议实现一个队列,第一个线程将输出发送到其中,第二个线程消费它。它也会修复竞态条件。有关实现的信息,请参见示例https://stackoverflow.com/a/4577987/4787126
https://stackoverflow.com/questions/40099114
复制相似问题