Boost.Interprocess使用指南(1)

來源:互聯網
上載者:User

2013-07-06 wcdj

Boost.Interprocess(下面簡稱BI)

http://www.boost.org/doc/libs/1_54_0/doc/html/interprocess.html#interprocess.intro.introduction_building_interprocess(Manual)

 

Introduction (BI簡介)

BuildingBoost.Interprocess

Testedcompilers

 

BI提供了一套強大且易用的IPC機制(interprocesscommunication and synchronization mechanisms):

  • Shared memory. (共用記憶體)
  • Memory-mapped files. (記憶體對應檔)
  • Semaphores, mutexes, condition variables and upgradable mutex types to place them in shared memory and memory mapped files.(在共用記憶體和記憶體對應檔中使用訊號量、互斥變數、條件變數和更進階的互斥類型)
  • Named versions of those synchronization objects, similar to UNIX/Windows sem_open/CreateSemaphore API. (這些同步對象的命名類似於平時我們常見的API)
  • File locking. (檔案鎖)
  • Relative pointers. (相對指標?)
  • Message queues. (訊息佇列)

Boost.Interprocess also offers higher-level interprocess mechanisms to allocatedynamically portions of a shared memory or a memory mapped file (in general, toallocate portions of a fixed size memory segment). Using these mechanisms,Boost.Interprocess
offersuseful tools to construct C++ objects, including STL-like containers, in sharedmemory and memory mapped files:(與此同時,BI也提供了更進階的處理序間通訊機制,比如,在共用記憶體或記憶體對應檔中動態分配一部分[一般是分配一個固定大小的記憶體段]。通過使用這些機制,BI擅長在共用記憶體或記憶體對應檔中建立C++對象,包括類似STL的容器)

  • Dynamic creation of anonymous and named objects in a shared memory or memory mapped file. (在共用記憶體或記憶體對應檔中建立匿名或命名物件)
  • STL-like containers compatible with shared memory/memory-mapped files. (在共用記憶體或記憶體對應檔中使用類似STL的容器)
  • STL-like allocators ready for shared memory/memory-mapped files implementing several memory allocation patterns (like pooling). (在共用記憶體或記憶體對應檔中使用類似STL的分配器,比如,記憶體池)
Building Boost.Interprocess (使用BI)

There is no need to compile Boost.Interprocess, since it's aheader only library. Just include your Boost header directory in your compilerinclude path. (BI不需要編譯,因為它是一個僅有標頭檔的庫,在使用時只需要將你下載的boost程式碼封裝含到你的標頭檔路徑即可,比如,linux下 g++ -o test test.cpp
–I./boost_1_52_0 -lrt)

Nothing to Build?

Most Boost libraries are header-only: they consistentirelyof header files containing templates and inline functions, andrequire no separately-compiled library binaries or specialtreatment
when linking.

Boost.Interprocess depends on
Boost.DateTime, which needs separatecompilation. However, the subset used byBoost.Interprocess does not need anyseparate compilation so the user can define BOOST_DATE_TIME_NO_LIBto avoid
Boost from trying to automatically link theBoost.DateTime. (BI依賴於Boost.DateTime,它需要單獨編譯。然而,被BI使用的子集是不需要單獨編譯的,因此使用者可以定義一個宏來避免Boost嘗試自動連結Boost.DateTime)

In POSIX systems, Boost.Interprocess uses pthread systemcalls to implement classes like mutexes, condition variables, etc... In someoperating systems, these POSIX calls are implemented in separate libraries thatare not automatically linked
by the compiler. For example, in some Linuxsystems POSIX pthread functions are implemented in librt.a library, so you mightneed to add that library when linking an executable or shared library that usesBoost.Interprocess.If you obtain linking
errors related to those pthread functions, please reviseyour system's documentation to know which library implements them. (在POSIX系統中,BI使用pthread系統調用來執行一些類,比如,互斥變數、條件變數等。在一些OS中,這些POSIX調用是在單獨的庫中被執行的,編譯器不會自動連結這些庫。例如,在一些Linux系統中POSIX的pthread函數是在librt.a庫中執行,因此當連結一個使用BI的可執行程式或共用庫時,你需要顯示添加那個庫。如果出現與pthread函數相關的連結錯誤時,請參考你的系統文檔瞭解pthread依賴與哪些庫)

Tested compilers (依賴的編譯器)

Boost.Interprocess has been tested in the following compilers/platforms: (OK,如果你使用的平台滿足以下條件,就開始嘗試使用BI吧)

  • Visual >= 7.1
  • GCC >= 4.1
  • Intel 11
Quick Guide for the Impatient (BI使用快速指南)

Usingshared memory as a pool of unnamed memory blocks (使用共用記憶體建立一個匿名記憶體池塊)

Creatingnamed shared memory objects (建立命名共用記憶體對象)

Usingan offset smart pointer for shared memory (在共用記憶體中使用位移智能指標)

Creatingvectors in shared memory (在共用記憶體中建立vector順序容器)

Creatingmaps in shared memory (在共用記憶體中建立map映射表容器)

Using sharedmemory as a pool of unnamed memory blocks (匿名記憶體池塊)

You can just allocate a portion of a shared memory segment,copy the message to that buffer, send the offset of that portion of sharedmemory to another process, and you are done. Let's see the example: (在共用記憶體中分配一部分buffer,並將訊息複製到這塊buffer中,然後將這部分共用記憶體的offset通知給另一個進程)

 

#include <boost/interprocess/managed_shared_memory.hpp>#include <cstdlib> //std::system#include <sstream>#include <iostream>using namespace boost::interprocess;int main (int argc, char *argv[]){if(argc == 1){  //Parent processstd::cout << "Parent process[" << getpid() << "]" << std::endl;//Remove shared memory on construction and destructionstruct shm_remove{shm_remove() {  shared_memory_object::remove("MySharedMemory"); }~shm_remove(){  shared_memory_object::remove("MySharedMemory"); }} remover;//Create a managed shared memory segmentmanaged_shared_memory segment(create_only, "MySharedMemory", 65536);//Allocate a portion of the segment (raw memory)managed_shared_memory::size_type free_memory = segment.get_free_memory();void * shptr = segment.allocate(1024/*bytes to allocate*/);//Check invariantif(free_memory <= segment.get_free_memory())return 1;//An handle from the base address can identify any byte of the shared//memory segment even if it is mapped in different base addressesmanaged_shared_memory::handle_t handle = segment.get_handle_from_address(shptr);std::stringstream s;s << argv[0] << " " << handle;s << std::ends;//Launch child processif(0 != std::system(s.str().c_str()))return 1;//Check memory has been freedif(free_memory != segment.get_free_memory())return 1;}else{std::cout << "child process[" << getpid() << "], sleep 10 secs..." << std::endl;sleep(10);std::cout << "child process[" << getpid() << "], sleep over..." << std::endl;//Open managed segmentmanaged_shared_memory segment(open_only, "MySharedMemory");//An handle from the base address can identify any byte of the shared//memory segment even if it is mapped in different base addressesmanaged_shared_memory::handle_t handle = 0;//Obtain handle valuestd::stringstream s; s << argv[1]; s >> handle;//Get buffer local address from handlevoid *msg = segment.get_address_from_handle(handle);//Deallocate previously allocated memorysegment.deallocate(msg);}std::cout << "process[" << getpid() << "] exit" << std::endl;return 0;}/* some tips:[1] basic_managed_shared_memory/boost_1_52_0/boost/interprocess/interprocess_fwd.hpp:221typedef basic_managed_shared_memory   <char      ,rbtree_best_fit<mutex_family>     ,iset_index> managed_shared_memory;[2] create_onlycreation_tags.hpp:46//!Value to indicate that the resource must//!be only createdstatic const create_only_t    create_only    = create_only_t();//!Value to indicate that the resource must//!be only openedstatic const open_only_t      open_only      = open_only_t();output:g++ -o shared_memory_unnamed shared_memory_unnamed.cpp  -I../boost_1_52_0 -lrt./shared_memory_unnamed Parent process[23793]child process[23794], sleep 10 secs...child process[23794], sleep over...process[23794] exitprocess[23793] exitcd /dev/shm/lsMySharedMemory  root  shm  sysconfig*/

待續

http://blog.csdn.net/great3779/article/details/7222202

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.