信号量是一种用于控制多个进程对共享资源访问的同步机制。它本质上是一个计数器,用于记录对资源的访问次数。信号量有两种基本操作:
互斥锁是一种特殊的二进制信号量,其值只能为0或1,用于实现资源的互斥访问。互斥锁的操作与信号量类似:
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
sem_t sem;
void* thread_func(void* arg) {
sem_wait(&sem); // P操作
printf("Thread is working\n");
sleep(1);
sem_post(&sem); // V操作
return NULL;
}
int main() {
sem_init(&sem, 0, 3); // 初始化信号量,初始值为3
pthread_t threads[5];
for (int i = 0; i < 5; ++i) {
pthread_create(&threads[i], NULL, thread_func, NULL);
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], NULL);
}
sem_destroy(&sem);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex;
void* thread_func(void* arg) {
pthread_mutex_lock(&mutex); // 加锁
printf("Thread is working\n");
sleep(1);
pthread_mutex_unlock(&mutex); // 解锁
return NULL;
}
int main() {
pthread_mutex_init(&mutex, NULL); // 初始化互斥锁
pthread_t threads[5];
for (int i = 0; i < 5; ++i) {
pthread_create(&threads[i], NULL, thread_func, NULL);
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex);
return 0;
}
sem_post
释放信号量,或者使用RAII技术管理信号量的生命周期。通过合理设计和使用信号量及互斥锁,可以有效避免并发编程中的常见问题,确保程序的正确性和稳定性。
领取专属 10元无门槛券
手把手带您无忧上云