我已经实现了一个简单的多线程程序,其中生产者访问全局变量并填充它,然后消费者打印它。
我是这样写的
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *prod(void);
void *cons(void);
unsigned int my_var = 0;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
int main()
{
pthread_t th1, th2;
int status;
status = pthread_create(&th1, NULL, (void*)prod, NULL);
if(status)
{
printf("Error creating thread 1 : %d\n", status);
exit(-1);
}
status = pthread_create(&th2, NULL, (void*)cons, NULL);
if(status)
{
printf("Error creating thread 2 : %d\n", status);
exit(-1);
}
pthread_join(th1, NULL);
pthread_join(th2, NULL);
return 0;
}
我的生产者函数是这样的:
void *prod(void)
{
while(1)
{
pthread_mutex_unlock(&mut);
printf("Enter the value : ");
scanf("%d", &my_var);
}
}
消费者函数是:
void *cons(void)
{
while(1)
{
printf("The value entered was %d\n", my_var);
pthread_mutex_lock(&mut);
}
}
此程序运行时输出准确,但模式不同,例如:
Enter the value : The value entered was 0
The value entered was 0
45
Enter the value : The value entered was 45
85
Enter the value : The value entered was 85
12
Enter the value : The value entered was 12
67
Enter the value : The value entered was 67
49
Enter the value : The value entered was 49
我发现很难纠正这种逻辑,因为它是线程概念的新手。 请帮我解决这个问题。
我的预期输出:
Enter the value : 45
The value entered is 45
.........................................
在一些答案和使用 mutex_cond_var 的指南之后。我在这样的函数中使用了它们:
void *prod(void)
{
while(1)
{
printf("Enter the value : ");
scanf("%d", &my_var);
pthread_cond_signal(&condition_var1);
pthread_mutex_unlock(&mut);
}
}
void *cons(void)
{
while(1)
{
pthread_mutex_lock(&mut);
pthread_cond_wait( &condition_var1, &mut );
printf("The value entered was %d\n", my_var);
}
}
结果输出:
Enter the value : 78
Enter the value : The value entered was 78
86
Enter the value : 15
Enter the value : The value entered was 15
35
Enter the value : 86
Enter the value : The value entered was 86
12
Enter the value : 65
Enter the value : The value entered was 65
78
Enter the value : 65
Enter the value : The value entered was 65
12
Enter the value : 35
Enter the value : The value entered was 35
请指导我清理代码以获得预期的输出。
最佳答案
从逻辑上讲,生产者代码可能会在消费者有机会运行之前运行多次。在这种情况下,您可能会错过一些输入的值。您将需要 2 个互斥量。 mutex_full
和 mutex_empty
。
初始值:mutex_full = NON_SIGNALED
和 mutex_empty = SIGNALED
Producer()
{
Wait(mutex_empty);
//produce code
Signal(mutex_full);
}
Consumer()
{
Wait(mutex_full);
//consumer code
Signal(mutex_empty);
}
关于c - 无法在我的多线程程序中找到错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37428482/