#include
#include
#include
#include
#include
static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t g_condition_notEmpty = PTHREAD_COND_INITIALIZER;
static pthread_cond_t g_condition_notFull = PTHREAD_COND_INITIALIZER;
#define CAPACITY 10
static char g_store[CAPACITY] = {' '};
static int g_outPutPosition = 0;
static int g_inPutPosition = 0;
char strData;
static int isBufferFull(void)
{
if(g_outPutPosition == ((g_inPutPosition + 1) % CAPACITY))
return 1;
else
return 0;
}
static int isBufferEmpty(void)
{
if(g_outPutPosition == g_inPutPosition)
return 1;
else
return 0;
}
static int putChToBuffer(char strData)
{
g_store[g_inPutPosition] = strData;
g_inPutPosition = (g_inPutPosition + 1) % CAPACITY;
return 0;
}
static int getChFromBuffer(char strData)
{
strData = g_store[g_outPutPosition];
g_store[g_outPutPosition] = '*';
g_outPutPosition = (g_outPutPosition + 1) % CAPACITY;
return 0;
}
void showStore(const char *who, const char *direction, char strData)
{
int index;
for (index = 0; index < CAPACITY; index++)
{
printf("%c", g_store[index]);
}
printf("%s %c(%s)n", direction, strData, who);
}
void *producerThreadFunc(void *arg)
{
const char *who = (char *)arg;
while(1)
{
//先获得锁
pthread_mutex_lock(&g_mutex);
if (1 == isBufferFull())
{
printf("仓库满了,%s线程不能进行生产!n", who);
pthread_cond_wait(&g_condition_notFull, &g_mutex);
printf("有人进行了消费,%s线程可以进行生产了!n", who);
}
strData = 'a' + rand() % 26;
putChToBuffer(strData);
showStore(who, " <--(input) ", strData);
pthread_cond_signal(&g_condition_notEmpty);
pthread_mutex_unlock(&g_mutex);
sleep(1);
}
return NULL;
}
void *consumerThreadFunc(void *arg)
{
const char *who = (const char *)arg;
while(1)
{
pthread_mutex_lock(&g_mutex);
if (1 == isBufferEmpty())
{
printf("仓库空了,%s等待!n", who);
pthread_cond_wait(&g_condition_notEmpty, &g_mutex);
printf("----------仓库有货,%s可以消费!n", who);
};
getChFromBuffer(strData);
showStore(who, "-->(output)", strData);
pthread_cond_signal(&g_condition_notFull);
//释放锁
pthread_mutex_unlock(&g_mutex);
sleep(1);
}
return NULL;
}
int main()
{
pthread_t producer_tid[2];
pthread_t consumer_tid[2];
pthread_create(&producer_tid[0], NULL, producerThreadFunc, "producer_1");
pthread_create(&producer_tid[1], NULL, producerThreadFunc, "producer_2");
pthread_create(&consumer_tid[0], NULL, consumerThreadFunc, "consumer_1");
pthread_create(&consumer_tid[1], NULL, consumerThreadFunc, "consumer_2");
pthread_join(producer_tid[0],NULL);
pthread_join(producer_tid[1],NULL);
pthread_join(consumer_tid[0],NULL);
pthread_join(consumer_tid[1],NULL);
getchar();
return 0;
}
编译:gcc xxx.c -o test -lpthread
执行:./test



