Mutex DLL - Example

Possible duplicate:
DLL thread security

Hi

Im writes a DLL file to MS VS C ++ express, which is simultaneously loaded into several client applications, it uses shared memory with other instances of the loaded DLL. Suppose a 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 it doCalcis called simultaneously from two or more clients, the system will fail. How can I create a mutex that stops other calls if the function is already called? Please give an example, since I spent the last two hours trying to find a decent one on the Internet;)

Thanks in advance.

+3
source share
3 answers

Code for each 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);
}
+4
source

" Mutex", MSDN . , CreateMutex, .

0

, , , . , struct, MapViewOfFile .

, , ( , ) .

.

0

Source: https://habr.com/ru/post/1783115/


All Articles