举例来说,这边从某处读取数据到缓冲区,那边将缓冲区数据进行处理。
pthread_cond_t data_cond; pthread_mutex_t data_mutex; #define DATA_SIZE 4096 int data_flag = 0; int data_size = 0; char data_buffer[DATA_SIZE]; void read_to_databuffer() { //init fd while (1) { //已读取的数据还没有被处理,等待。或者用另外的条件锁? while (data_flag == 1) { usleep(1000); continue; } pthread_mutex_lock(&data_mutex); data_size = read(fd, data_buffer, DATA_SIZE); //已经没有数据,中断。 if (data_size <= 0) { pthread_mutex_unlock(&data_mutex); break; } //设置数据标志,发出通知 data_flag = 1; pthread_cond_signal( &data_cond); pthread_mutex_unlock(&data_mutex); } //release } void databuffer_to_process() { while (1) { pthread_mutex_lock(&data_mutex); //没有数据,进入条件锁 if (data_flag == 0) { //有人问,两边都先lock……其实这里有一个先释放锁的动作。 pthread_cond_wait(&data_cond, &data_mutex); } //处理数据 //结束处理 data_flag = 0; pthread_mutex_unlock(&data_mutex); } //release } void start() { pthread_t tid1, tid2; pthread_mutex_init(&data_mutex, NULL); pthread_cond_init( &data_cond, NULL); pthread_create(&tid1, NULL, read_to_databuffer, NULL); pthread_create(&tid2, NULL, databuffer_to_process, NULL); }