結合Boost官網
使用的是boost::interprocess庫。
共享內存通常是進程間通訊最快的形式。
boost::interprocess::shared_memory_object
託管共享內存
boost::interprocess::managed_shared_memory
設置內部數據採用 construct<template T>("name")(num);
name:名字作爲識別標籤設計。是爲了find方法。
num:設置的數據值
find 方法的返回值是pair類型,
std::pair<int *, size_t> p = managed_shd.find<int>("name");
int * 是地址, size_t 是對象數,
舉個簡單的例子區分,上面的 construct是創建了單個對象,同樣加上[ ]構建數組,如construct<template T>("name")[ ](num);
如果創建的不是基本類型(int, char等等)呢?
Boost.Interprocess 在 boost/interprocess/allocators/allocator.hpp
文件中提供了boost::interprocess::allocator
類的定義。
typedef boost::interprocess::allocator<char, boost::interprocess::managed_shared_memory::segment_manager> CharAllocator;
typedef boost::interprocess::basic_string<char, char_traits<char>, CharAllocator> String;
①CharAllocator的構造形式:
//!An STL compatible allocator that uses a segment manager as
//!memory source. The internal pointer type will of the same type (raw, smart) as
//!"typename SegmentManager::void_pointer" type. This allows
//!placing the allocator in shared memory, memory mapped-files, etc...
template<class T, class SegmentManager>
class allocator
②String的構造形式
charT:數據存儲類型
Traits:traits(charT)
Allocator:內存分配方式:①CharAllocator
//! \tparam CharT The type of character it contains.
//! \tparam Traits The Character Traits type, which encapsulates basic character operations
//! \tparam Allocator The allocator, used for internal memory management.
#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED
template <class CharT, class Traits = std::char_traits<CharT>, class Allocator = new_allocator<CharT> >
#else
template <class CharT, class Traits, class Allocator>
#endif
class basic_string
其實也不用上面這麼麻煩,我試驗了下也可以直接用string類,demo如下:
boost::interprocess::managed_shared_memory managed_shd(boost::interprocess::open_or_create, "HighScore", 1024);
string *s = managed_shd.find_or_construct<string>("String")(string("Hello"));
atomic_func(Func &f):接受無返回值類型的函數
如:
boost::interprocess::managed_shared_memory managed_shd(...);
managed_shd.atomic_func(boost::bind(F, boost::ref(managed_shd));
boost::ref在第三章函數對象有說明:起到引用調用參數的作用。
進程間同步
在修改共享內存存儲的數據時,需要加上進程鎖。
互斥鎖:boost::interprocess::named_mutex。
條件變量:boost::interprocess::named_condition。
練習題:
1、創建一個通過共享內存通訊的客戶端/服務器應用程序。 文件名稱應該作爲命令行參數傳遞給客戶端應用程序。 這個文件存儲在服務器端應用程序啓動的目錄下,這個文件應經由共享內存發送給服務器端應用程序。
解答在github開源了