Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DLL Mutex - an example [duplicate]

Possible Duplicate:
DLL thread safety

Hi

Im writting a DLL file in MS VS C++ express, which is loaded in multiple client applications at the same time, it uses shared memory with the other instances of the loaded DLL. Let us assume the DLL looks something like this:

#include stdafx.h  
#pragma data_seg (".TEST")  
//Shared variables  
#pragma data_seg ()  
#pragma comment(linker, "/section:.TEST,RWS")  
_DLLAPI void __stdcall doCalc()  
{  
//Do critical stuff  
}

If doCalc is called simultaneously from two or more clients the system will crash. How would I create a Mutex that "stalls" other calls if the function has already been called? Please give an example, as I have spent the last two hours trying to find a decent one on the internet ;)

Thanks in advance.

like image 460
sigvardsen Avatar asked Apr 09 '26 11:04

sigvardsen


1 Answers

The code of every process:

// At the start of every process
HANDLE sharedMemoryMutex = CreateMutex(NULL, FALSE, "My shared memory mutex");

// When you want to access shared memory:
DWORD dwWaitResult = WaitForSingleObject(sharedMemoryMutex, INFINITE);

if (dwWaitResult == WAIT_OBJECT_0 || dwWaitResult == WAIT_ABANDONED)
{
   if (dwWaitResult == WAIT_ABANDONED)
   {
      // Shared memory is maybe in inconsistent state because other program
      // crashed while holding the mutex. Check the memory for consistency
      ...
   }

   // Access your shared memory
   ...

   // After this line other processes can access shared memory
   ReleaseMutex(sharedMemoryMutex);
}
like image 175
Dialecticus Avatar answered Apr 12 '26 00:04

Dialecticus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!