在 Linux 中,信号量(semaphore)是一种用于进程间同步的机制。它通常用于控制对共享资源的访问,以防止多个进程同时修改同一资源导致的数据不一致性。C++ 中可以使用 POSIX 信号量(semaphore.h)来实现这一功能。
以下是一个简单的示例,展示了如何在 C++ 中使用 POSIX 信号量:
#include <iostream>
#include <semaphore.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
sem_t semaphore;
sem_init(&semaphore, 0, 1); // 第二个参数表示信号量的属性,0 表示在当前进程中可见;第三个参数表示信号量的初始值
sem_wait() 函数等待信号量:sem_wait(&semaphore);
在这里执行需要同步的操作,例如访问共享资源。
使用 sem_post() 函数释放信号量:
sem_post(&semaphore);
sem_destroy(&semaphore);
下面是一个完整的示例,展示了如何在两个进程之间使用信号量同步对共享资源的访问:
#include <iostream>
#include <semaphore.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
int main() {
sem_t semaphore;
sem_init(&semaphore, 0, 1);
int fd = open("shared_file.txt", O_RDWR | O_CREAT, 0666);
if (fd == -1) {
perror("open");
return 1;
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) { // 子进程
sem_wait(&semaphore);
std::cout << "Child process is accessing the shared resource." << std::endl;
sleep(2);
std::cout << "Child process is done." << std::endl;
sem_post(&semaphore);
} else { // 父进程
sem_wait(&semaphore);
std::cout << "Parent process is accessing the shared resource." << std::endl;
sleep(2);
std::cout << "Parent process is done." << std::endl;
sem_post(&semaphore);
}
close(fd);
sem_destroy(&semaphore);
return 0;
}
在这个示例中,我们创建了一个名为 shared_file.txt 的共享文件,并使用信号量确保父子进程不会同时访问它。