Robust CRITCAL_SECTION for shared memory?

痴心易碎 提交于 2019-12-08 19:55:35

问题


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).


回答1:


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?



来源:https://stackoverflow.com/questions/13532189/robust-critcal-section-for-shared-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!