Boost.Interprocess使用指南(1)

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 allocate dynamically portions of a shared memory or a memory mapped file (in general, to allocate portions of a fixed size memory segment). Using these mechanisms, Boost.Interprocess offers useful tools to construct C++ objects, including STL-like containers, in shared memory 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 compiler include 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 consist entirely of header files containing templates and inline functions, and require no separately-compiled library binaries or special treatment when linking.


Boost.Interprocess depends on Boost.DateTime, which needs separate compilation. However, the subset used by Boost.Interprocess does not need any separate compilation so the user can define BOOST_DATE_TIME_NO_LIB to avoid Boost from trying to automatically link the Boost.DateTime. (BI依赖于Boost.DateTime,它需要单独编译。然而,被BI使用的子集是不需要单独编译的,因此用户可以定义一个宏来避免Boost尝试自动链接Boost.DateTime)

In POSIX systems, Boost.Interprocess uses pthread system calls to implement classes like mutexes, condition variables, etc... In some operating systems, these POSIX calls are implemented in separate libraries that are not automatically linked by the compiler. For example, in some Linux systems POSIX pthread functions are implemented in librt.a library, so you might need to add that library when linking an executable or shared library that uses Boost.Interprocess. If you obtain linking errors related to those pthread functions, please revise your 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使用快速指南)

Using shared memory as a pool of unnamed memory blocks (使用共享内存创建一个匿名内存池块)

Creating named shared memory objects (创建命名共享内存对象)

Usingan offset smart pointer for shared memory (在共享内存中使用偏移智能指针)

Creating vectors in shared memory (在共享内存中创建vector顺序容器)

Creating maps in shared memory (在共享内存中创建map映射表容器)

Using shared memory 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 shared memory 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 process

		std::cout << "Parent process[" << getpid() << "]" << std::endl;

		//Remove shared memory on construction and destruction
		struct shm_remove
		{
			shm_remove() {  shared_memory_object::remove("MySharedMemory"); }
			~shm_remove(){  shared_memory_object::remove("MySharedMemory"); }
		} remover;

		//Create a managed shared memory segment
		managed_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 invariant
		if(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 addresses
		managed_shared_memory::handle_t handle = segment.get_handle_from_address(shptr);
		std::stringstream s;
		s << argv[0] << " " << handle;
		s << std::ends;
		//Launch child process
		if(0 != std::system(s.str().c_str()))
			return 1;
		//Check memory has been freed
		if(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 segment
		managed_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 addresses
		managed_shared_memory::handle_t handle = 0;

		//Obtain handle value
		std::stringstream s; s << argv[1]; s >> handle;

		//Get buffer local address from handle
		void *msg = segment.get_address_from_handle(handle);

		//Deallocate previously allocated memory
		segment.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:221
typedef basic_managed_shared_memory
   <char
      ,rbtree_best_fit<mutex_family>
	     ,iset_index>
		 managed_shared_memory;

[2] create_only
creation_tags.hpp:46
//!Value to indicate that the resource must
//!be only created
static const create_only_t    create_only    = create_only_t();

//!Value to indicate that the resource must
//!be only opened
static 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] exit
process[23793] exit

cd /dev/shm/
ls
MySharedMemory  root  shm  sysconfig

*/

待续

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


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值