MemoryManager.h 2.29 KB
/*
 * MemoryManager.h
 *
 *  Created on: 15 gru 2018
 *      Author: mariuszo
 */

#ifndef MEMORYMANAGER_H_
#define MEMORYMANAGER_H_

#include <semaphore.h>
#include <string>
#include <atomic>
#include "shm.h"
#include "DataBlock.h"
#include "enums.h"
/*
#include <limits.h>
#include <linux/limits.h>
#include <unistd.h>
#include <stdint.h>

*/
#define FULLYPARALLEL

#ifndef FULLYPARALLEL
#include <mutex>
#endif

struct memoryManagementData {
	size_t dataRingBufferSize;
	size_t dataSlotsRingBufferSize;
	sem_t dataSlotsSemaphore;
#ifndef FULLYPARALLEL
	uint64_t allocData;
	uint64_t releaseData;
#else
	std::atomic<uint64_t> allocData;
	std::atomic<uint64_t> releaseData;
#endif
	std::atomic<size_t> freeSize;
};


class MemoryManagerBase {
	const std::string& m_name;
	
	shmRing m_shmDataRingBuffer;
	shm m_shmMemoryManagementData;

	uint8_t* m_dataRingBuffer;
	dataSlot* m_dataSlotsRingBuffer;
	memoryManagementData* m_memoryManagementData;
	uint64_t m_dataSlotIDMask;
	uint8_t m_dataSlotIDShift;
	uint64_t m_dataSlotAddrMask;
protected:
	MemoryManagerBase(const std::string& name);
	virtual ~MemoryManagerBase();

	void attach();
	void create(const size_t& dataRingBufferSize, const size_t& dataSlotsRingbufferSize);
	void destroy();

	inline DataBlock getDataBlock(const off_t& dataSlotID, const off_t& slotID) { return DataBlock(m_dataSlotsRingBuffer[dataSlotID], m_dataRingBuffer, slotID);}

	DataBlock alloc(const size_t& size, const uint64_t& timeoutns=UINT64_MAX);
	inline void free(const DataBlock& dataBlock) { free(dataBlock.blockID()); }
	void free(off_t dataSlotID);
public:
	inline const size_t& dataSlotsRingBufferSize() const {return m_memoryManagementData->dataSlotsRingBufferSize;}
};

template <access_type A> class MemoryManager : public MemoryManagerBase {
public:
	MemoryManager(const std::string& name): MemoryManagerBase(name) {}
	virtual ~MemoryManager() {}
	using MemoryManagerBase::attach;
	using MemoryManagerBase::getDataBlock;
};

template <> class MemoryManager<access_type::access_master> : public MemoryManagerBase {
public:
	MemoryManager(const std::string& name) : MemoryManagerBase(name){}
	virtual ~MemoryManager(){
		destroy();
	}

	using MemoryManagerBase::create;
	using MemoryManagerBase::destroy;
	using MemoryManagerBase::alloc;
	using MemoryManagerBase::free;
};

#endif /* MEMORYMANAGER_H_ */