Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Robust CRITCAL_SECTION for shared memory?

We have some data structures that we are sharing across processes on Windows. (Via a shared data segment in a DLL that's loaded by all these processes.)

We need to synchronize some accesses and we measured that the performance hit of using a Win32 Mutex is too costly.

CRITICAL_SECTION cannot be put into shared memory due to some of it's advanced features.

This leaves us with the requirement of a simple locking/mutex solution based directly on the Interlocked* family of function on Win32.

Before rolling my own I'd like to see if there's robust implementations out there that handle the requirement of being lightweight, fast and working in shared memory for multiple processes, but it seems that this is something that's a tad hard to google for me. (And, anyway, the CodeProject hits, well it's often hard to tell whether it's toy code or "robust".)

So what I'd need could probably be called a user-mode recursive mutex that works for multiple processes when put in shared memory on Windows (note that only the locking part needs to be handled savely, I can live with restrictions / additional requirements for initialization).

like image 775
Martin Ba Avatar asked Nov 23 '12 15:11

Martin Ba


1 Answers

Shared memory is a popular topic currently,

Try boost::InterProcess - which provides mechanisms that could be used and utilizes common code x-platform.

http://www.boost.org/doc/libs/1_52_0/doc/html/interprocess/sharedmemorybetweenprocesses.html

The other reason is that the library provides mechanisms for synchronisation and other IPC mechanisms that may be useful in the future.

http://www.boost.org/doc/libs/1_52_0/doc/html/interprocess/synchronization_mechanisms.html

For reference the thing uses Atomic OPs as well for the mutex:

http://www.boost.org/doc/libs/1_52_0/boost/interprocess/sync/spin/mutex.hpp

inline void spin_mutex::lock(void)
{
   do{
      boost::uint32_t prev_s = ipcdetail::atomic_cas32(const_cast<boost::uint32_t*>(&m_s), 1, 0);

      if (m_s == 1 && prev_s == 0){
            break;
      }
      // relinquish current timeslice
      ipcdetail::thread_yield();
   }while (true);
}

Also from the "chat below" this post look at the top answer for : Is there a difference between Boost's scoped mutex and WinAPi's critical section?

like image 62
Caribou Avatar answered Oct 13 '22 10:10

Caribou