Linux操作系统提供了多种线程同步机制,以确保多线程环境下共享资源的正确访问。以下是一些常用的线程同步机制:
以下是一个使用互斥锁和条件变量的简单示例代码,展示了如何在C语言中使用pthread库实现线程同步:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define BUFFER_SIZE 5 int buffer[BUFFER_SIZE]; int count = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_producer = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_consumer = PTHREAD_COND_INITIALIZER; void *producer(void *arg) { for (int i = 0; i < 10; ++i) { pthread_mutex_lock(&mutex); while (count == BUFFER_SIZE) { // 缓冲区满,等待消费者消费 pthread_cond_wait(&cond_producer, &mutex); } buffer[count++] = i; printf("Produced: %d\n", i); // 通知消费者可以消费了 pthread_cond_signal(&cond_consumer); pthread_mutex_unlock(&mutex); } pthread_exit(NULL); } void *consumer(void *arg) { for (int i = 0; i < 10; ++i) { pthread_mutex_lock(&mutex); while (count == 0) { // 缓冲区空,等待生产者生产 pthread_cond_wait(&cond_consumer, &mutex); } printf("Consumed: %d\n", buffer[--count]); // 通知生产者可以生产了 pthread_cond_signal(&cond_producer); pthread_mutex_unlock(&mutex); } pthread_exit(NULL); } int main() { pthread_t id1, id2; pthread_create(&id1, NULL, producer, NULL); pthread_create(&id2, NULL, consumer, NULL); pthread_join(id1, NULL); pthread_join(id2, NULL); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_producer); pthread_cond_destroy(&cond_consumer); return 0; } 通过上述代码,可以看到如何使用互斥锁和条件变量来同步生产者和消费者线程,确保缓冲区的正确使用。