Points to consider when implementing shared memory
I am planning to implement boost's shared memory between a Server (C++) and client (C# application). There is only reader and one writer and frequency of data s开发者_如何学编程hare (read and write) is thousands of time per millisecond.
What are the risks involved?
thousands of times per ms doesn't say much. If it's one byte a time that's not a lot. If it's more.. well, it all depends on how much.
I would advise against sharing memory. I would suggest "don't communicate by sharing, share by communicating". If, once you're done, profiling shows that the extra memory copy is indeed the bottleneck, then, yea, maybe some interop-based shared memory solution is the fix. Often you find out that's not the case though.
I just want to make comments about shared memory in general
- Expect the shared memory to be mapped into different places in virtual memory. This means that passing pointers between one process and the next is useless, you must use offsets from the shared memory base address
- You will not have access to malloc/new and free/delete heap management functions but you do have nice block of memory to set up your own memory management objects.
- You must devise a clear ownership model of which process has access to which piece of memory.
- Any access to objects shared across the processes (such as bookkeeping objects) must be protected by a mutex
- Look for strategies that minimize the time spent while the mutex is locked, freelists are your friend.
- In any producer consumer model ensure that you have thought clearly about flow control. You must not overflow or underflow the shared space. Semaphores are your friend.
I think that about covers it. And I agree with the above, rather use IPC to copy memory unless your really have to use shared memory, the pitfalls may eat you alive.
Well, as of .NET 3.5, there's no support for shared memory. You'd have to use P/Invoke, which is a pain. The bigger problem is that C#'s memory model is not very conducive to sharing with C++.
edit
As an additional risk, it's going to require holding OS handles, which means that any mistake could result in a leak that will not be fixed by anything short of killing the process. You can protect against much of this by using SafeHandle
instead of IntPtr
.
精彩评论