如何确保Producer和Consumer函数无限运行并且一个接一个地运行?例如:首先,我希望用户输入数组,然后使用者函数打印输入的数组,然后再次要求用户输入数组。
/* Headers */
pthread_mutex_t mutex;
pthread_cond_t cond,cond1;
void *producer(void *arg);
void *consumer(void *arg);
static int n;
int consumerFlag[100];
void *producer(void *arg)
{
pthread_mutex_lock(&mutex);
while(1)
{
printf("\n Enter no of terms");
scanf("%d",&n);
int i;
printf("\n Enter consumer flag array");
for (i = 0; i < n; i++)
{
scanf(" %d",&consumerFlag[i]);
pthread_mutex_unlock(&mutex);
}
pthread_cond_signal(&cond);
usleep(1000);
}
}
void *consumer(void *arg)
{
int i;
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("\nConsumer Function");
while(1)
{
printf("\nConsumer thread waiting");
for (i = 0; i < n; i++)
{
printf("\nConsumerFlag %d = %d", i, consumerFlag[i]);
pthread_mutex_unlock(&mutex);
}
}
}
int main()
{
int i=0;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_t pThread, cThread;
pthread_create(&pThread, 0, producer, 0);
pthread_create(&cThread, 0, consumer,0);
pthread_join(pThread,NULL);
pthread_join(cThread, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
首先,我希望用户输入数组,然后使用者函数打印输入的数组,然后再次要求用户输入数组。
您的代码中几乎没有重大问题。
因此在生产者中,您需要生成数据,向消费者发送信号并等待消费者确认数据被消耗。您需要另外设置一个标志,以考虑生产者线程在消费者线程之前获得锁定的情况。在这种情况下,当生产者发送信号时,消费者不会进入while循环。所以消费者无法捕捉到信号。
void *producer(void *arg)
{
pthread_mutex_lock(&mutex);
while(1)
{
printf("\n Enter no of terms");
scanf("%d",&n);
int i;
printf("\n Enter consumer flag array");
for (i = 0; i < n; i++)
{
scanf(" %d",&consumerFlag[i]);
//pthread_mutex_unlock(&mutex); //Should not be unlocked in loop
}
data_produced_flag = 1; //A flag to indicate data is ready. Should be initialized to 0 before thread creation. It is required if producer produces before consumer thread goes to pthread_cond_wait()
pthread_cond_signal(&cond_producer); //Should send signal with mutex locked
//usleep(1000); //Not required as it is going to wait for signal from consumer
pthread_cond_wait(&cond_consumer, &mutex); //Wait for confirmation that data is consumed
}
pthread_mutex_unlock(&mutex);
}
在使用者功能中,您应该检查数据是否已经生成。如果没有产生,等待来自生产者的信号。当数据可用时,消费并向生产者发出信号以获取新数据。
void *consumer(void *arg)
{
int i;
pthread_mutex_lock(&mutex);
//pthread_cond_wait(&cond, &mutex); //Wait inside loop
printf("\nConsumer Function");
while(1)
{
if(0 == data_produced_flag)
{
printf("\nConsumer thread waiting");
pthread_cond_wait(&cond_producer, &mutex); //Wait for signal from producer
}
//else
//{
//Data is already produced. No need to wait.
//}
//Data is available for consumption
for (i = 0; i < n; i++)
{
printf("\nConsumerFlag %d = %d", i, consumerFlag[i]);
//pthread_mutex_unlock(&mutex); //We are in the process of consumption. Don't unlock mutex.
}
data_produced_flag = 0; //Reset the flag. Ready for new data.
pthread_cond_signal(&cond_consumer); //Indicate that data is consumed
}
pthread_mutex_unlock(&mutex);
}