【Linux】线程同步 -- 条件变量 | 生产者消费者模型 | 自旋锁 |读写锁
在Linux环境下,可以使用条件变量(pthread\_cond\_t)、互斥锁(pthread\_mutex\_t)和自旋锁(spinlock)等来实现线程同步。以下是实现生产者和消费者模型的例子:
#include <stdio.h>
#include <pthread.h>
#define BUFFER_SIZE 1
int buffer[BUFFER_SIZE];
int read_index = 0;
int write_index = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER;
void* producer(void* arg) {
int i;
for (i = 0; i < BUFFER_SIZE; i++) {
pthread_mutex_lock(&mutex);
while ((write_index + 1) % BUFFER_SIZE == read_index) {
pthread_cond_wait(¬_full, &mutex);
}
buffer[write_index] = i;
write_index = (write_index + 1) % BUFFER_SIZE;
pthread_cond_signal(¬_empty);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void* consumer(void* arg) {
int i;
for (i = 0; i < BUFFER_SIZE; i++) {
pthread_mutex_lock(&mutex);
while (write_index == read_index) {
pthread_cond_wait(¬_empty, &mutex);
}
printf("Consumed: %d\n", buffer[read_index]);
read_index = (read_index + 1) % BUFFER_SIZE;
pthread_cond_signal(¬_full);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t producer_thread, consumer_thread;
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
return 0;
}
在这个例子中,我们使用了条件变量not_full
和not_empty
来同步生产者和消费者。当缓冲区满时,生产者等待not_full
条件,当缓冲区为空时,消费者等待not_empty
条件。一旦条件满足,相应的pthread_cond_signal
函数被调用来唤醒其他线程。
注意,这里使用了一个有界缓冲区来演示生产者消费者模型,大小为1,以简化示例。在实际应用中,缓冲区大小可以根据需要进行调整。
评论已关闭