Last active
December 23, 2016 00:25
-
-
Save alexsilva/ed656e1147040e8a8da4 to your computer and use it in GitHub Desktop.
Client model that uses shared memory as a communication channel.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by alex on 21/10/2015. | |
// | |
#include <boost/interprocess/shared_memory_object.hpp> | |
#include <boost/interprocess/mapped_region.hpp> | |
#include <boost/interprocess/sync/scoped_lock.hpp> | |
#include <iostream> | |
#include <cstring> | |
#include "shared_data.h" | |
#include "client.h" | |
using namespace boost::interprocess; | |
class SharedMemory { | |
public: | |
SharedMemory() { | |
shm = new shared_memory_object( | |
open_only, // only create | |
sharedmem_key, // name | |
read_write // read-write mode | |
); | |
region = new mapped_region(*shm, read_write); | |
void *addr = region->get_address(); | |
msg = static_cast<Message *>(addr); // shared obj | |
} | |
~SharedMemory() { | |
delete shm; | |
delete region; | |
} | |
mapped_region *get_region() { | |
return region; | |
} | |
shared_memory_object *get_shm() { | |
return shm; | |
} | |
Message *get_message() { | |
return msg; | |
} | |
private: | |
mapped_region *region; | |
shared_memory_object *shm; | |
Message *msg; | |
}; | |
static SharedMemory *sharedMemory = NULL; | |
static PyObject *start(PyObject *self, PyObject *args) { | |
sharedMemory = new SharedMemory(); | |
Py_INCREF(Py_None); | |
return Py_None; | |
} | |
static PyObject *send_message(PyObject *self, PyObject *args) { | |
Message *message = sharedMemory->get_message(); | |
scoped_lock<interprocess_mutex> lock(message->mutex); | |
clock_t before; | |
before = clock(); | |
sprintf(message->data, "client message"); | |
message->client.notify_all(); | |
message->server.wait(lock); // wait the server | |
printf("TIME: %.10f \n\n", ((float) clock() - before) / CLOCKS_PER_SEC); | |
Py_INCREF(Py_None); | |
return Py_None; | |
} | |
static PyObject *stop(PyObject *self, PyObject *args) { | |
delete sharedMemory; | |
Py_INCREF(Py_None); | |
return Py_None; | |
} | |
static PyMethodDef methods[] = { | |
{"start", start, METH_VARARGS, "client start"}, | |
{"send_message", send_message, METH_VARARGS, "send message to server"}, | |
{"stop", stop, METH_VARARGS, "client stop"}, | |
{NULL, NULL, 0, NULL} /* Sentinel */ | |
}; | |
PyMODINIT_FUNC initclient(void) { | |
PyObject *mod; | |
mod = Py_InitModule("client", methods); | |
if (mod == NULL) | |
return; | |
PyObject * err = PyErr_NewException((char *) "client.error", NULL, NULL); | |
Py_INCREF(err); | |
PyModule_AddObject(mod, "error", err); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment