【发布时间】:2018-09-26 16:39:41
【问题描述】:
我有两个线程通过循环缓冲区进行通信。
/* Initialize not_full semaphore to a count of BUFFER_SIZE */
sem_init(¬_full_semaphore, 0, BUFFER_SIZE);
/* Initialize not_empty semaphore to a count of 0 */
sem_init(¬_empty_semaphore, 0, 0);
void producer_thread (void) {
int item
int head = 0;
while(true) {
item = produce_item();
sem_wait(¬_full_semaphore);
mutex_lock(&circular_buffer_mutex);
/* Insert item into the buffer */
circular_buffer[head] = item;
/* Increment head offset and wrap if necessary */
head = (head == BUFFER_SIZE - 1) ? 0 : head + 1;
mutex_unlock(&circular_buffer_mutex);
sem_post(¬_empty_semaphore);
}
}
void consumer_thread (void){
int item;
int tail = 0;
while(true) {
sem_wait(¬_empty_semaphore);
mutex_lock(&circular_buffer_mutex);
/* Remove item from the buffer */
item = circular_buffer[tail];
/* Increment tail offset and wrap if necessary */
tail = (tail == BUFFER_SIZE - 1) ? 0 : tail + 1;
mutex_unlock(&circular_buffer_mutex);
sem_post(¬_full_semaphore);
consume_item(item);
}
我的问题是我真的需要互斥锁吗?在我看来,生产者和消费者不可能同时访问相同的内存。在生产者完成写入并通过 not_empty 信号量发出信号之前,消费者不会读取。 not_full 信号量将阻止生产者回绕并再次写入。所以在我看来我不需要互斥锁,但我发现的所有示例都使用了它。
【问题讨论】:
-
在只有一个生产者和一个消费者的特定情况下,并且给定一个头索引只有生产者访问和尾索引只有消费者访问的队列结构,你可以不用互斥锁。
标签: c multithreading mutex