DLL thread safety

2019-03-06 01:58发布

问题:

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(".SHARED_SPACE_NAME"). In this shared memory space there are some vectors that can be modified. Lets assume we have a function in the DLL body called doCalc():

_DLLAPI void __stdcall doCalc(int argument)  
{  
    //Add to vector  
    //Loop through vector  
    //Erase from vector  
    //etc.  
}

If doCalc is called at the same time from two or more client applications the system will crash. I want the doCalc calls to "wait in line" for the previous call to finish - like it was a single-threaded application. So that if client 1 calls and then immediately after client 2 calls, then client 1 should finish the function, and then client 2 should run the function.

The best solution would be to run the DLL as a single thread but I have searched the internet a I do not think it is possible.

I have tried searching the internet for this issue, and I have come up with something about making the function static would make it thread safe.

I have also read that C++0x somehow will make this thread-safe. But that it is not supported in MS VC express.

I have no experience in multithreading, so I hope you can help. Thanks in advance.

回答1:

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.



回答2:

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.



回答3:

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.