看看一个非常好的生产者/消费者的多线程例子:
Code Example: Producer/Consumer with Bounded Length (Using Condition Variables)
void *producer(void *arg)
{
request_t *request;
while(1)
{
request = get_request();
pthread_mutex_lock(&requests_lock);
while (length >= 10)
pthread_cond_wait(&requests_producer, &requests_lock);
add(request);
length++;
pthread_mutex_unlock(&requests_lock);
pthread_cond_signal(&requests_consumer);
}
}
void *consumer(void *arg)
{
request_t *request;
while(1)
{
pthread_mutex_lock(&requests_lock);
while (length == 0)
pthread_cond_wait(&requests_consumer, &requests_lock);
request = remove();
length--;
pthread_mutex_unlock(&requests_lock);
pthread_cond_signal(&requests_producer);
process_request(request);
}
}
看pthread代码,发现pthread的条件变量用信号量实现的
阅读(966) | 评论(0) | 转发(0) |