From 8f68612e3777a9f338140542844a9d31afaf4520 Mon Sep 17 00:00:00 2001 From: Max Breitenfeldt <git@mxbr.me> Date: Wed, 30 Jun 2021 15:48:49 +0200 Subject: [PATCH] Refactor shared memory initialization --- Src/Model/BioTrackerTrackingAlgorithm.cpp | 40 +++++++++++------------ Src/Model/BioTrackerTrackingAlgorithm.h | 2 +- 2 files changed, 20 insertions(+), 22 deletions(-) diff --git a/Src/Model/BioTrackerTrackingAlgorithm.cpp b/Src/Model/BioTrackerTrackingAlgorithm.cpp index 7d304dc..69cc502 100644 --- a/Src/Model/BioTrackerTrackingAlgorithm.cpp +++ b/Src/Model/BioTrackerTrackingAlgorithm.cpp @@ -18,24 +18,6 @@ using json = nlohmann::json; -void* init_shm_mmap(const char *path, int len) { - int fd = shm_open(path, O_RDWR, 0); - if (fd == -1) { - throw "shm_open"; - } - - void *shm_buf = mmap(NULL, len, - PROT_READ | PROT_WRITE, - MAP_SHARED, fd, 0); - close(fd); - - if (shm_buf == MAP_FAILED) { - throw "mmap"; - } - - return shm_buf; -} - BioTrackerTrackingAlgorithm::BioTrackerTrackingAlgorithm(IController *parent, IModel* parameter, IModel* trajectory) : IModelTrackingAlgorithm(parent) { @@ -55,7 +37,7 @@ BioTrackerTrackingAlgorithm::~BioTrackerTrackingAlgorithm() stop_python(); } -void BioTrackerTrackingAlgorithm::request_shared_memory() { +void BioTrackerTrackingAlgorithm::init_shared_memory() { json j = { { "type", "request_shared_memory" }, { "width", _imageX }, @@ -65,7 +47,23 @@ void BioTrackerTrackingAlgorithm::request_shared_memory() { auto res = _sock.recv(_zmq_msg, zmq::recv_flags::none); auto msg = json::parse(_zmq_msg.to_string_view()); std::string shm_path = msg["path"].get<std::string>(); - _shm_img = (float*)init_shm_mmap(shm_path.c_str(), _imageX * _imageY * sizeof(float)); + int shm_len = _imageX * _imageY * sizeof(float); + + int fd = shm_open(shm_path.c_str(), O_RDWR, 0); + if (fd == -1) { + throw "shm_open"; + } + + void *shm_buf = mmap(NULL, shm_len, + PROT_READ | PROT_WRITE, + MAP_SHARED, fd, 0); + close(fd); + + if (shm_buf == MAP_FAILED) { + throw "mmap"; + } + + _shm_img = (float*)shm_buf; } void BioTrackerTrackingAlgorithm::stop_python() { @@ -112,7 +110,7 @@ void BioTrackerTrackingAlgorithm::doTracking(std::shared_ptr<cv::Mat> p_image, u if (_imageX != p_image->size().width || _imageY != p_image->size().height) { _imageX = p_image->size().width; _imageY = p_image->size().height; - request_shared_memory(); + init_shared_memory(); Q_EMIT emitDimensionUpdate(_imageX, _imageY); } diff --git a/Src/Model/BioTrackerTrackingAlgorithm.h b/Src/Model/BioTrackerTrackingAlgorithm.h index e1b136b..782314c 100644 --- a/Src/Model/BioTrackerTrackingAlgorithm.h +++ b/Src/Model/BioTrackerTrackingAlgorithm.h @@ -38,7 +38,7 @@ public Q_SLOTS: void receiveParametersChanged(); private: - void request_shared_memory(); + void init_shared_memory(); void start_python(); void stop_python(); -- GitLab