在共享内存 POSIX 中创建队列
在我的实现中,我使用 mmap
为进程间通信分配共享内存。在这个共享内存中,我初始化了一个队列(我将第一个和最后一个指针设置为 NULL)。
问题是如何将新项目推入队列。通常我会使用 malloc 来分配我的“队列项结构”,然后指向它,但我不能使用它,可以吗?我需要以某种方式在共享内存中分配它。我可能可以使用另一个 mmap
并将项目推到那里然后指向它,但这似乎不对,因为我必须多次这样做。
这可以简单地完成还是我应该考虑不同的解决方案?
感谢您的任何想法。
For my implementation I am using mmap
for allocating shared memory for interprocess communication. In this shared memory I initialize a queue (I set first and last pointer to NULL).
The problem is how to push new item into the Queue. Normally I would use a malloc
to allocate my 'queue item struct' and then point to it, but I can't use that, can I? I need to allocate it somehow in the shared memory. I probably could use another mmap
and push the item there and then point to it, but it doesn't seem right, because I would have to do that multiple times.
Can this be done simply or I should think about different solutions?
Thanks for any ideas.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在共享内存中创建队列的一般规则:
1)永远不要使用指针作为共享元素,因为操作系统可能会在不同的进程中选择不同的虚拟地址。始终使用共享内存视图基地址或数组索引的偏移量,或者无论如何与位置无关的东西。
2)您必须手动对共享内存进行分区。例如,您必须知道队列可能包含多少个项目,并确定共享区域的尺寸,以便它可以包含“haeder”(插入索引和提取索引...)和项目数组。通常定义一个包含正确大小的“标头”和“项数组”的结构就足够了:内存大小是 sizeof(your_struct),其地址是 mmap 返回的地址。
3)仔细考虑多线程和多处理问题。如果可以接受访问线程可能会阻塞,则使用互斥体保护对共享内存的访问。但如果你想创建一个“非阻塞”队列,你至少必须使用原子操作来改变相关字段,并考虑任何可能的时序问题。
问候
General rules to create a queue in shared memory:
1) Never use pointers as shared elements, because the OS may choose different virtual addresses in different processes. Always use offsets from the shared memory view base address, or array indices, or anyway something that is position-independent.
2) You have to manually partition your shared memory. E.g. you must know how many items your queue may contain, and dimension the shared area so it can contain the "haeder" (insertion index and extraction index...) and the item array. It's often enough to define a structure that contains both the "header" and the "item array" of the correct size: the memory size is sizeof(your_structure), its address is the one returned by mmap.
3) Carefully consider multithreading and multiprocessing issues. Protect the access to the shared memory with a mutex if it's acceptable that the accessing threads may block. But if you want to create a "non-blocking" queue, you must at least use atomic operations to change the relevant fields, and consider any possible timing issue.
Regards