Linux 中的互斥锁和条件变量是用于多线程编程中同步和协调线程执行的重要机制。
互斥锁(Mutex):
条件变量(Condition Variable):
如果在 Linux 中使用互斥锁和条件变量遇到问题,可能是以下原因:
以下是一个使用互斥锁和条件变量的简单示例代码(C 语言):
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int count = 0;
void* producer(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
count++;
printf("Produced, count = %d
", count);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(1);
}
return NULL;
}
void* consumer(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(&cond, &mutex);
}
count--;
printf("Consumed, count = %d
", count);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t producer_thread, consumer_thread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
在上述示例中,生产者线程生产数据(增加 count
),消费者线程消费数据(减少 count
)。通过互斥锁保护 count
的访问,条件变量用于在 count
为 0 时让消费者等待,生产者生产数据后通知消费者。
领取专属 10元无门槛券
手把手带您无忧上云