我正在实现一个多进程库,为共享内存提供数据结构。但是我现在遇到了麻烦,我在子进程中修改了共享的Hash对象,但父进程仍然没有读取更改的值。
示例代码:https://play.crystal-lang.org/#/r/6n34
使用相同的指针修改,为什么它不起作用?
当您分叉进程时,会复制其内存,同时保留相同的虚拟内存地址。
您只是将指针放入共享内存部分,因此在fork之前的内存布局是:
+--------------------+ +--------------------+
| Shared memory | | Parent heap |
| | | |
| | | |
| Virtual address | | +---------+ |
| of --------------> | Hash | |
| | | +---------+ |
| | | |
+--------------------+ +--------------------+
在fork之后,指针分别引用每个进程的私有内存:
+--------------------+ +--------------------+
| Shared memory | | Parent heap |
| | | |
| | | |
| Virtual address | | +---------+ |
| of --------------> | Hash | |
| | | | +---------+ |
| | | | |
+--------------------+ +--------------------+
|
|
| +--------------------+
| | Child heap |
| | |
| | |
| | +---------+ |
+--------> | Hash | |
| +---------+ |
| |
+--------------------+
因此,当您取消引用子项中的指针时,您只触及子堆中的对象。
您需要做的是将所有实际数据放入共享内存中。这对于标准Crystal数据类型来说很棘手,因为它们依赖于能够请求新内存并让它由垃圾收集器管理。因此,您需要实现可以在共享内存上工作的GC。
但是,如果您只有固定数量的数据,比如几个数字或固定大小的字符串,您可以利用Crystal的值类型来使事情更好一点:
module SharedMemory
def self.create(type : T.class, size : Int32) forall T
protection = LibC::PROT_READ | LibC::PROT_WRITE
visibility = LibC::MAP_ANONYMOUS | LibC::MAP_SHARED
ptr = LibC.mmap(nil, size * sizeof(T), protection, visibility, 0, 0).as(T*)
Slice(T).new(ptr, size)
end
end
record Data, point : Int32 do
setter point
end
shared_data = SharedMemory.create(Data, 1)
shared_data[0] = Data.new 23
child = Process.fork
if child
puts "Parent read: '#{shared_data[0].point}'"
child.wait
puts "Parent read: '#{shared_data[0].point}'"
else
puts "Child read: '#{shared_data[0].point}'"
# Slice#[] returns the object rather than a pointer to it,
# so given Data is a value type, it's copied to the local
# stack and the update wouldn't be visible in the shared memory section.
# Therefore we need to get the pointer using Slice#to_unsafe
# and dereference it manually with Pointer#value
shared_data.to_unsafe.value.point = 42
puts "Child changed to: '#{shared_data[0].point}'"
end
Parent read: '23'
Child read: '23'
Child changed to: '42'
Parent read: '42'
https://play.crystal-lang.org/#/r/6nfn
这里的问题是你不能将任何Reference
类型如String
或Hash
放入结构中,因为这些只是指向每个进程的私有地址空间的指针。 Crystal提供了类型和API,使得共享例如字符串更容易一些,即Slice
和String#to_slice
等,但是每次要传递它或分别将其转换回来时,你必须将它复制到共享存储器中或从共享存储器中复制它。必须提前知道你的(最大)字符串长度。