Win32 Read/Write Lock Using Only Critical Sections

前端 未结 10 1315
攒了一身酷
攒了一身酷 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:35

    I don't think this can be done without using at least one kernel-level object (Mutex or Semaphore), because you need the help of the kernel to make the calling process block until the lock is available.

    Critical sections do provide blocking, but the API is too limited. e.g. you cannot grab a CS, discover that a read lock is available but not a write lock, and wait for the other process to finish reading (because if the other process has the critical section it will block other readers which is wrong, and if it doesn't then your process will not block but spin, burning CPU cycles.)

    However what you can do is use a spin lock and fall back to a mutex whenever there is contention. The critical section is itself implemented this way. I would take an existing critical section implementation and replace the PID field with separate reader & writer counts.

    0 讨论(0)
  • 2020-12-14 12:37

    Take a look at the book "Concurrent Programming on Windows" which has lots of different reference examples for reader/writer locks.

    0 讨论(0)
  • 2020-12-14 12:39

    This is an old question but perhaps someone will find this useful. We developed a high-performance, open-source RWLock for Windows that automatically uses Vista+ SRWLock Michael mentioned if available, or otherwise falls back to a userspace implementation.

    As an added bonus, there are four different "flavors" of it (though you can stick to the basic, which is also the fastest), each providing more synchronization options. It starts with the basic RWLock() which is non-reentrant, limited to single-process synchronization, and no swapping of read/write locks to a full-fledged cross-process IPC RWLock with re-entrance support and read/write de-elevation.

    As mentioned, they dynamically swap out to the Vista+ slim read-write locks for best performance when possible, but you don't have to worry about that at all as it'll fall back to a fully-compatible implementation on Windows XP and its ilk.

    0 讨论(0)
  • 2020-12-14 12:47

    Check out the spin_rw_mutex from Intel's Thread Building Blocks ...

    spin_rw_mutex is strictly in user-land and employs spin-wait for blocking

    0 讨论(0)
  • 2020-12-14 12:49

    Here is the smallest solution that I could come up with:

    http://www.baboonz.org/rwlock.php

    And pasted verbatim:

    /** A simple Reader/Writer Lock.
    
    This RWL has no events - we rely solely on spinlocks and sleep() to yield control to other threads.
    I don't know what the exact penalty is for using sleep vs events, but at least when there is no contention, we are basically
    as fast as a critical section. This code is written for Windows, but it should be trivial to find the appropriate
    equivalents on another OS.
    
    **/
    class TinyReaderWriterLock
    {
    public:
        volatile uint32 Main;
        static const uint32 WriteDesireBit = 0x80000000;
    
        void Noop( uint32 tick )
        {
            if ( ((tick + 1) & 0xfff) == 0 )     // Sleep after 4k cycles. Crude, but usually better than spinning indefinitely.
                Sleep(0);
        }
    
        TinyReaderWriterLock()                 { Main = 0; }
        ~TinyReaderWriterLock()                { ASSERT( Main == 0 ); }
    
        void EnterRead()
        {
            for ( uint32 tick = 0 ;; tick++ )
            {
                uint32 oldVal = Main;
                if ( (oldVal & WriteDesireBit) == 0 )
                {
                    if ( InterlockedCompareExchange( (LONG*) &Main, oldVal + 1, oldVal ) == oldVal )
                        break;
                }
                Noop(tick);
            }
        }
    
        void EnterWrite()
        {
            for ( uint32 tick = 0 ;; tick++ )
            {
                if ( (tick & 0xfff) == 0 )                                     // Set the write-desire bit every 4k cycles (including cycle 0).
                    _InterlockedOr( (LONG*) &Main, WriteDesireBit );
    
                uint32 oldVal = Main;
                if ( oldVal == WriteDesireBit )
                {
                    if ( InterlockedCompareExchange( (LONG*) &Main, -1, WriteDesireBit ) == WriteDesireBit )
                        break;
                }
                Noop(tick);
            }
        }
    
        void LeaveRead()
        {
            ASSERT( Main != -1 );
            InterlockedDecrement( (LONG*) &Main );
        }
        void LeaveWrite()
        {
            ASSERT( Main == -1 );
            InterlockedIncrement( (LONG*) &Main );
        }
    };
    
    0 讨论(0)
  • 2020-12-14 12:52

    If you can target Vista or greater, you should use the built-in SRWLock's. They are lightweight like critical sections, entirely user-mode when there is no contention.

    Joe Duffy's blog has some recent entries on implementing different types of non-blocking reader/writer locks. These locks do spin, so they would not be appropriate if you intend to do a lot of work while holding the lock. The code is C#, but should be straightforward to port to native.

    You can implement a reader/writer lock using critical sections and events - you just need to keep enough state to only signal the event when necessary to avoid an unnecessary kernel mode call.

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