DLL thread safety

前端 未结 3 859
南方客
南方客 2021-01-26 06:52

I am developing a DLL in MS VC express c++ that will be loaded in multiple client applications at the same time, the DLL has a shared memory space created using data_seg(\

相关标签:
3条回答
  • 2021-01-26 07:22

    Looks like you need a system-wide mutex that will protect your critical section of code (the code that mustn't run simultaneously). Making the function static has nothing to do with it, because it doesn't prevent different applications from running it at the same time.

    0 讨论(0)
  • 2021-01-26 07:31

    The Windows API to use here would be CreateMutex. Create a named mutex object. As you need to manipulate the shared data, call WaitForSingleObject with the mutex handle, and when you are done, call ReleaseMutex. Each thread that calls WaitForSingleObject takes ownership of the mutex and any other thread that calls WaitForSingleObject will stall, until the owning thread calls ReleaseMutex.

    Of course, I don't belive you can do what you want to do:

    1. Dlls may be mapped in at different addresses in each process space. If so, all pointers will be incorrect.
    2. C++ does not allow fine grained control over allocations and has many implicit allocations, especially when dealing with STL objects. I don't belive that you can get the vector to store all the relevant data in the shared area.

    You are going to have to do this with C style raw arrays.

    0 讨论(0)
  • 2021-01-26 07:36

    I think that Boost.Interprocess is exactly what you need. It will solve both, the synchronization problem, and the one that Jim Brissom said in his comment that you even haven't thought about yet.

    0 讨论(0)
提交回复
热议问题