在Linux环境中,信号量(Semaphore)是一种用于控制多个进程或线程对共享资源的访问的同步机制。信号量可以用来防止并发访问导致的竞态条件(Race Condition)。
信号量(Semaphore):
P操作(等待操作):
V操作(释放操作):
释放信号量通常是通过V操作来实现的。以下是一个使用C语言和POSIX信号量API的示例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
sem_t sem;
void* thread_func(void* arg) {
// 等待信号量
sem_wait(&sem);
printf("Thread %ld acquired the semaphore
", (long)arg);
// 模拟对共享资源的访问
sleep(1);
// 释放信号量
sem_post(&sem);
printf("Thread %ld released the semaphore
", (long)arg);
return NULL;
}
int main() {
// 初始化信号量,初始值为1
if (sem_init(&sem, 0, 1) == -1) {
perror("sem_init");
exit(EXIT_FAILURE);
}
pthread_t threads[5];
for (long i = 0; i < 5; ++i) {
if (pthread_create(&threads[i], NULL, thread_func, (void*)i) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], NULL);
}
// 销毁信号量
sem_destroy(&sem);
return 0;
}
信号量泄漏:
sem_wait
调用都有对应的sem_post
调用。死锁:
信号量初始化错误:
sem_init
的返回值,确保初始化成功。通过合理使用信号量,可以有效地管理并发访问,提高系统的稳定性和可靠性。
领取专属 10元无门槛券
手把手带您无忧上云