编程进程同步算法(例如克隆/分叉、信号量)时从哪里开始
我正在编写一个模拟进程同步的程序。我正在尝试在 C++ 中实现分叉和信号量技术,但开始时遇到困难。我是否只是创建一个进程并将其从一开始就发送到fork?该程序是否只是在父/子进程之间来回的无限循环?如何在 C++ 中创建“共享内存”的概念、显式内存地址或只是一些全局变量?我只需要了解程序流程的整体结构/想法。任何参考将不胜感激。
I am writing a program that simulates process synchronization. I am trying to implement the fork and semaphore techniques in C++, but am having trouble starting off. Do I just create a process and send it to fork from the very beginning? Is the program just going to be one infinite loop that goes back and forth between parent/child processes? And how do you create the idea of 'shared memory' in C++, explicit memory address or just some global variable? I just need to get the overall structure/idea of the flow of the program. Any references would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从您的问题中不清楚您是否真正意味着模拟或者您是否正在尝试从 C++ 访问常见的进程同步功能。您对
fork
的引用表明 Linux 是您的目标。一旦创建新进程,您就不再模拟进程同步,而是使用操作系统的本机同步功能。
在 Linux 上,要获取共享内存,您可以使用 mmap(可能使用 MAP_ANON),然后调用 fork。生成的内存区域将被共享。您还可以使用 System V 共享内存(名称以“shm”开头的系统调用)。一旦调用 fork,子进程就是父进程的副本,但普通的全局变量最终不会被共享:子进程获得一个新副本。因此需要mmap或shm。
在 Windows 上,没有什么比 fork 更好的了。您必须使用命名共享内存对象或映射文件来建立共享内存。新进程必须进行必要的系统调用来打开共享内存对象或将公共文件映射到其地址空间。
如果您确实想要构建一个模拟器——一个在内部管理进程和共享内存的单个进程,您可能需要挑选一本描述 Linux 或 Windows 在该领域内部工作的书籍。
It is unclear from your question whether you really mean simulation or whether you are trying to access common process synchronization features from C++. Your reference to
fork
suggests that Linux is your target.As soon as you create a new process, you're not simulating process synchronization, you are using the native synchronization capabilities of the operating system.
On Linux, to get shared memory, you would use mmap (perhaps with MAP_ANON) and then call fork. The resulting memory region will be shared. You can also use System V Shared Memory (the system calls whose names begin with 'shm'). Once you call fork, the child is a copy of the parent, but ordinary global variables don't end up shared: the child gets a new copy. Thus the need for mmap or shm.
On Windows, there is nothing like fork. You have to use named shared memory objects, or mapped files, to establish shared memory. The new process must make the necessary system calls to open the shared memory object or map the common file into its address space.
If you really do want to build a simulator -- a single process that internally manages processes and shared memory, you might want to pick up one of the various books that describe the internal working of Linux or Windows in this area.