我们已经研究过,如果我们处理多线程问题,那么我们使用一种称为mutex的线程同步方法,它允许锁定关键部分,以便其他线程不会干扰并进入阻塞状态,直到互斥锁解锁关键部分.
但是我在我的程序中做了这个事情,但是这个程序的输出与mutex的概念不匹配.如果我错了,请纠正我.
码
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#define MAX 10
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int toConsume=0;
int i;
void* consumer(void *ptr) {
pthread_mutex_lock(&the_mutex);
while(i<MAX)
{
/* protect buffer */
while (toConsume <= 0) /* If there is nothing in the buffer then wait */
{
printf("Waiting Thread id:%lu \n",pthread_self());
pthread_cond_wait(&condc, &the_mutex);
}
pthread_mutex_unlock(&the_mutex); /* release the buffer */
sleep(2);
pthread_mutex_lock(&the_mutex); /* protect buffer */
toConsume--;
i++;
}
pthread_mutex_unlock(&the_mutex); /* release the buffer */ …Run Code Online (Sandbox Code Playgroud)