Upgraded Win32 Read / Write Lock

I am looking for an updated read-write lock for win32 with the pthreads rwlock behavior, where read locks can be raised and lowered.

What I want:

pthread_rwlock_rdlock( &lock ); ...read... if( some condition ) { pthread_rwlock_wrlock( &lock ); ...write... pthread_rwlock_unlock( &lock ); } ...read... pthread_rwlock_unlock( &lock ); 

The update behavior is not required by posix, but it works on linux on mac.

I currently have a working implementation (event-based, semaphore and critical section) that can be updated, but the update may fail when readers are active. If it does not work, you need to read unlock + double check + write lock.

What I have:

 lock.rdlock(); ...read... if( some condition ) { if( lock.tryupgrade() ) { ...write... lock.unlock(); return; } else { lock.unlock(); // <- here, other threads may alter the condition -> lock.wrlock(); if( some condition ) { // so, re-check required ...write... } lock.unlock(); return; } } ...read... lock.unlock(); 

EDIT: Bounty:

I'm still in search, but I want to add some limitations: it is used only inside the process (therefore, based on critical sections it is normal, WIN32 mutexes are not OK), and it should be pure WIN32 API (without MFC, ATL, etc.) . Acquiring read locks should be fast (so getting a read lock should not go into a critical section on its fast path). Is a solution based on InterlockedIncrement possible?

+4
source share
2 answers

The boost shared_mutex supports read (shared) and write locks (unique) and temporary updates from shared locks to unique ones.

Example for boost shared_mutex (multiple reads / single record)?

I do not recommend writing your own, it is a difficult thing to get right and hard to check carefully.

+2
source

pthread library is the Portable Threads library. This means that it is also supported on windows;) See: Pthreads-w32 .

Also, consider using OpenMP instead of locks: the compiler extension provides portable critical sections, a thread stream model, tasks, and more! MS C ++ supports this technology, as well as g ++ on Linux.

Hooray!:)

0
source

All Articles