boost之Interprocess库,进程间通讯库之condition/mutex/scoped_lock

公共头文件doc_anonymous_condition_shared_data.h:

#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>

struct trace_queue
{
	enum { LineSize = 100 };

	trace_queue() : message_in(false) { }

	//
	boost::interprocess::interprocess_mutex mutex;
	boost::interprocess::interprocess_condition cond_empty;
	boost::interprocess::interprocess_condition cond_full;

	//
	char items[LineSize];
	bool message_in;
};

写进程:

#include <iostream>
#include <string>
using namespace std;

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>

#include "doc_anonymous_condition_shared_data.h"

using namespace boost::interprocess;

int main(int argc, char*argv[])
{
	struct shm_remove
	{
		shm_remove() { shared_memory_object::remove("MySharedMemory"); }
		~shm_remove() { shared_memory_object::remove("MySharedMemory"); }
	};

	shared_memory_object shm(create_only, "MySharedMemory", read_write);
	shm.truncate(sizeof(trace_queue));

	mapped_region region(shm, read_write);

	void *addr = region.get_address();
	trace_queue *data = new (addr) trace_queue;

	for(int i=0; i<100; i++)
	{
		scoped_lock<interprocess_mutex> lock(data->mutex);
		if(data->message_in)
			data->cond_full.wait(lock);

		if(99 == i) sprintf(data->items, "%s", "last message");
		else sprintf(data->items, "%s_%d", "my_trace", i);
		cout<<data->items<<endl;

		data->cond_empty.notify_one();

		data->message_in = true;
	}

	return 0;
}


读进程

#include <iostream>
#include <string>
using namespace std;

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>

#include "doc_anonymous_condition_shared_data.h"

using namespace boost::interprocess;

void main(int argc, char *argv[])
{
	shared_memory_object shm(open_only, "MySharedMemory", read_write);
	mapped_region region(shm, read_write);

	void *addr = region.get_address();
	trace_queue *data = static_cast<trace_queue*>(addr);

	bool end_loop = false;
	do 
	{
		scoped_lock<interprocess_mutex> lock(data->mutex);
		if(!data->message_in)
			data->cond_empty.wait(lock);

		cout<<data->items<<endl;
		if(0 == strcmp(data->items, "last message"))
		{
			end_loop = true;
		}
		else
		{
			data->message_in = false;
			data->cond_full.notify_one();
		}
	} while (!end_loop);

	shm.remove("MySharedMemory");
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值