在 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 的共享文件,并使用信号量确保父子进程不会同时访问它。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1486511.html