resource_ownership.hpp 1.79 KB
Newer Older
Swann Perarnau's avatar
Swann Perarnau committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
#ifndef __RESOURCE_OWNERSHIP_HPP__
#define __RESOURCE_OWNERSHIP_HPP__
#include "utils.hpp"
#include <csignal>

/*NOTE: Always own a resource before trying to set it exclusive!
 * */
template <typename T>
class Resource_ownership
{
	private:
		int _nb_owners;
		bool _exclusive;
		T _resource;

		void assign(const Resource_ownership& ro)
		{
			_resource = ro._resource; 
			_exclusive = ro._exclusive; 
			_nb_owners = ro._nb_owners;
		}

	public:
		explicit Resource_ownership(T res) 
		{_resource = res; _nb_owners = 0; _exclusive = false;}

		Resource_ownership(T res, bool exclusive)
		{_resource = res; _nb_owners = 0; _exclusive = exclusive;}

		Resource_ownership(const Resource_ownership& ro)
		{assign(ro);}

		Resource_ownership& operator = (const Resource_ownership& orig)
		{
			if(this != &orig)
				assign(orig);
			return *this;
		}

		~Resource_ownership(){}

		bool operator ==(const Resource_ownership& rhs) const
		{
			return _resource == rhs._resource;
		}

		inline void increment_owners() 
		{
			//std::raise(SIGINT);
			THROW_ON_FORBIDDEN_ACTION_IF(!can_increment_owners(), 
					"Exclusivity violation!"); 
			++_nb_owners;
		} 

		inline void decrement_owners() {if(--_nb_owners == 0) _exclusive = false;}

		inline void set_exclusive(bool status)
		{
			//std::raise(SIGINT);
			THROW_ON_FORBIDDEN_ACTION_IF(status && !can_set_exclusive(), 
					"Exclusivity violation!"); 
			_exclusive = status;
		}

		inline bool can_set_exclusive() const {return _nb_owners <= 1;}

		inline bool can_own_exclusively() const {return _nb_owners == 0;}

		inline bool can_increment_owners() const {return !_exclusive || _nb_owners == 0;};

		T& get_resource() {return _resource;}

		void reset(){_nb_owners = 0; _exclusive = false;}

		bool is_used() {return _nb_owners != 0;}


};
#endif //__RESOURCE_OWNERSHIP_HPP__