条件变量与互斥锁的优势在于条件变量能够减少竞争的次数, 如下例子中所示,当head为空时,消费者线程阻塞在pthread_cond_wait , 这时生产这能够直接获得锁,而不用与消费者线程竞争.
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
typedef struct pie
{
int idx;
struct pie *next;
} PID, *PPIE;
PPIE head = NULL;
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread_fun(void *arg)
{
while(1)
{
pthread_mutex_lock(&mtx);
while (head == NULL)
{
pthread_cond_wait(&cond, &mtx);
}
PPIE p = head;
head = head->next;
p->next = NULL;
printf("========>consumer %ld %d\n", reinterpret_cast<long>(arg), p->idx);
free(p);
pthread_mutex_unlock(&mtx);
usleep(rand()%500000);
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t thread;
srand(1000);
for (long i=0; i<5; i++)
{
int ret = pthread_create(&thread, NULL,
thread_fun, (void*)i);
if (ret != 0)
{
printf("pthread_create error\n");
return 1;
}
pthread_detach(thread);
}
while(1)
{
PPIE p = (PPIE)malloc(sizeof(struct pie));
if (p)
{
pthread_mutex_lock(&mtx);
p->idx = rand()%1000;
p->next = head;
head = p;
printf("===========>productor %d\n", p->idx);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
usleep(rand()%100000);
}
}
return 0;
}