在Linux多线程编程中,PV操作(也称为信号量操作)是一种用于线程同步和互斥的重要机制。PV操作基于信号量(semaphore)这一概念,信号量是一个整型变量,用于控制多个线程对共享资源的访问。
以下是一个使用POSIX信号量实现线程同步的简单示例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_THREADS 5
sem_t sem;
void* thread_func(void* arg) {
int thread_id = *(int*)arg;
// P操作:等待信号量
sem_wait(&sem);
printf("Thread %d is accessing the shared resource.
", thread_id);
sleep(1); // 模拟访问共享资源的时间
printf("Thread %d is done accessing the shared resource.
", thread_id);
// V操作:释放信号量
sem_post(&sem);
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];
// 初始化信号量,初始值为1
sem_init(&sem, 0, 1);
// 创建线程
for (int i = 0; i < NUM_THREADS; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]);
}
// 等待线程结束
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
// 销毁信号量
sem_destroy(&sem);
return 0;
}
通过合理地使用PV操作,可以有效地解决多线程编程中的同步和互斥问题,提高程序的正确性和稳定性。
领取专属 10元无门槛券
手把手带您无忧上云