Win32 Read/Write Lock Using Only Critical Sections

前端 未结 10 1314
攒了一身酷
攒了一身酷 2020-12-14 12:20

I have to implement a read/write lock in C++ using the Win32 api as part of a project at work. All of the existing solutions use kernel objects (semaphores and mutexes) tha

10条回答
  •  有刺的猬
    2020-12-14 12:57

    Look my implementation here:

    https://github.com/coolsoftware/LockLib

    VRWLock is a C++ class that implements single writer - multiple readers logic.

    Look also test project TestLock.sln.

    UPD. Below is the simple code for reader and writer:

    LONG gCounter = 0;
    
    // reader
    
    for (;;) //loop
    {
      LONG n = InterlockedIncrement(&gCounter); 
      // n = value of gCounter after increment
      if (n <= MAX_READERS) break; // writer does not write anything - we can read
      InterlockedDecrement(&gCounter);
    }
    // read data here
    InterlockedDecrement(&gCounter); // release reader
    
    // writer
    
    for (;;) //loop
    {
      LONG n = InterlockedCompareExchange(&gCounter, (MAX_READERS+1), 0); 
      // n = value of gCounter before attempt to replace it by MAX_READERS+1 in InterlockedCompareExchange
      // if gCounter was 0 - no readers/writers and in gCounter will be MAX_READERS+1
      // if gCounter was not 0 - gCounter stays unchanged
      if (n == 0) break;
    }
    // write data here
    InterlockedExchangeAdd(&gCounter, -(MAX_READERS+1)); // release writer
    

    VRWLock class supports spin count and thread-specific reference count that allows to release locks of terminated threads.

提交回复
热议问题