条件变量的使用是为了提高程序的效率,单单使用互斥量会造成阻塞。
条件变量的创建:pthread_cond_t cond;
相关函数
int pthread_cond_init(pthread_cond_t * cond,const pthread_condattr_t * attr);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex,const struct timespec *restrict abstime);
int pthread_cond_broadcast(pthread_cond_t *cond)
int pthread_cond_signal(pthread_cond_t *cond)
pthead_cond_wait参数:
pthread_cond_t *restrict cond:条件变量;
pthread_mutex_t *restruct mutex:互斥量。
pthread_cond_timedwait多了一个超时。
pthread_cond_wait运行过程,当不满足条件是会释放互斥锁,然后挂起该线程,直到满足条件后该线程回到运行状态同时上锁。
pthread_cond_timedwait则超时后会尝试去获取一次互斥量,然后返回错误码。
pthread_cond_signal发送条件来唤醒至少一个线程
pthread_cond_broadcast唤醒所有线程
demo(生产者消费者)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define BUF_SIZE 5
struct buf_c
{
int buf[BUF_SIZE]; //缓冲区大小
pthread_mutex_t mutex;
pthread_cond_t nofull; //两个条件
pthread_cond_t noempty;
int write_p; //写指针的位置
int read_p; //读指针的位置
};
struct buf_c buf_t;
void* producer(void *arg)
{
int cnt=0;
pthread_mutex_lock(&buf_t.mutex);
while(cnt < 10)
{
if(buf_t.write_p - buf_t.read_p > BUF_SIZE - 1)
{
printf("buf has fulled,stop to produce\n"); //缓冲区满了,停止生产,等待有空位
pthread_cond_wait(&buf_t.nofull,&buf_t.mutex);
}
else
{
buf_t.buf[buf_t.write_p % BUF_SIZE] = cnt;
pthread_cond_signal(&buf_t.noempty);
printf("produce the %d\n",cnt);
cnt++;
buf_t.write_p++;
pthread_mutex_unlock(&buf_t.mutex);
sleep(1);
}
}
pthread_mutex_unlock(&buf_t.mutex);
return (void *)0;
}
void* customer(void *arg)
{
pthread_mutex_lock(&buf_t.mutex);
while(1)
{
if(buf_t.read_p == buf_t.write_p)
{
printf("buf has emptied,stop to custome\n");
pthread_cond_wait(&buf_t.noempty,&buf_t.mutex); //缓冲区没有数据,等待生产者生产数据
}
else
{
printf("custome the %d\n",buf_t.buf[buf_t.read_p % BUF_SIZE]);
pthread_cond_signal(&buf_t.nofull);
if(++buf_t.read_p == 10)
{
printf("custome completed\n");
pthread_mutex_unlock(&buf_t.mutex);
return (void *)0;
}
pthread_mutex_unlock(&buf_t.mutex);
sleep(1);
}
}
}
void init_buf(void)
{
pthread_mutex_init(&buf_t.mutex,NULL);
pthread_cond_init(&buf_t.nofull,NULL);
pthread_cond_init(&buf_t.noempty,NULL);
buf_t.write_p = 0;
buf_t.read_p = 0;
}
int main()
{
pthread_t thread1,thread2;
void *ret;
pthread_create(&thread1, NULL, producer, NULL);
pthread_create(&thread2, NULL, customer, NULL);
init_buf();
pthread_join(thread1,&ret);
pthread_join(thread2,&ret);
return 0;
}
可以看到生产者一秒生产一个数据,然后消费者拿走。