【发布时间】:2016-05-25 05:29:44
【问题描述】:
我实现了一个简单的多线程程序,生产者访问全局变量并填充它,然后消费者打印它。
我主要是这样写的
#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;
}
我的 Producer 函数是这样的:
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
请指导我清理代码以获得预期的输出。
【问题讨论】:
-
您需要一些机制来确保首先执行
prod,然后它可以向cons发送信号以打印该值。 ,, 想到一个pthread_cond_t条件变量。它们用于线程在满足特定条件时相互发送信号(因此cons可以等待,prod可以打印然后接受用户输入,之后它可以向cons发送信号以打印值然后停止。在@ 987654336@ 已打印,它可以向prod发送信号以再次查询用户等)。这是一个很好的示例教程:computing.llnl.gov/tutorials/pthreads -
请注意:
prod和cons函数不带参数。但他们should 采取void *。好像应该有警告 -
你不应该在这里做你想做的事情。对于互斥锁,在 Pthread 手册中提到 如果线程尝试解锁未锁定的互斥锁或解锁的互斥锁,则会导致未定义的行为。 如果您需要实现生产者消费者同步,则应该使用
pthread_cond_wait(),pthread_cond_signal()。
标签: c multithreading mutex