现在的位置: 首页 > 综合 > 正文

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

2018年10月05日 ⁄ 综合 ⁄ 共 2181字 ⁄ 字号 评论关闭

公共头文件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");
}

抱歉!评论已关闭.