Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » Developing U++ » UppHub » Shared object with auto locking strategy
Shared object with auto locking strategy [message #17378] Sun, 10 August 2008 13:39 Go to next message
gridem is currently offline  gridem
Messages: 45
Registered: August 2008
Member
There is code to use automatic locking for shared object among threads

#ifndef _shared_shared_hpp_
#define _shared_shared_hpp_

#include <Core/Core.h>

namespace Upp
{
	
template<typename T>
struct Shared
{
	struct Locker
	{
		Locker(T& value, Mutex& mutex) : m_value(value), m_lock(mutex) {}
		T* operator->()
		{
			return &m_value;
		}
		T& operator*()
		{
			return m_value;
		}
		T* operator&()
		{
			return &m_value;
		}

	private:
		T& m_value;
		Mutex::Lock m_lock;
	};

	static Locker get()
	{
		return Locker(Single<T>(), mutex);
	}
	
private:
	static Mutex mutex;
};

template<typename T>
Mutex Shared<T>::mutex;

template<typename T>
struct RWShared
{
	struct ReadLocker
	{
		ReadLocker(const T& value, RWMutex& mutex) : m_value(value), m_lock(mutex) {}
		const T* operator->()
		{
			return &m_value;
		}
		const T& operator*()
		{
			return m_value;
		}
		const T* operator&()
		{
			return &m_value;
		}

	private:
		const T& m_value;
		RWMutex::ReadLock m_lock;
	};

	struct WriteLocker
	{
		WriteLocker(T& value, RWMutex& mutex) : m_value(value), m_lock(mutex) {}
		T* operator->()
		{
			return &m_value;
		}
		T& operator*()
		{
			return m_value;
		}
		T* operator&()
		{
			return &m_value;
		}

	private:
		T& m_value;
		RWMutex::WriteLock m_lock;
	};

	static ReadLocker read()
	{
		return ReadLocker(Single<T>(), mutex);
	}
	
	static WriteLocker write()
	{
		return WriteLocker(Single<T>(), mutex);
	}
	
private:
	static RWMutex mutex;
};

template<typename T>
RWMutex RWShared<T>::mutex;

}

#endif


example usage:
struct A
{
	int a;
	int b;
	
	int getSum() const
	{
		return a + b;
	}
};
...
	RWShared<A>::write()->a = 2;
	RWShared<A>::write()->b = 3;
	Cout() << RWShared<A>::read()->getSum() << "\n";
Re: Shared object with auto locking strategy [message #17380 is a reply to message #17378] Sun, 10 August 2008 16:32 Go to previous message
captainc is currently offline  captainc
Messages: 278
Registered: December 2006
Location: New Jersey, USA
Experienced Member
Very cool, definitely will use this. Thank you.
Previous Topic: Extended Logging Package
Next Topic: My Simple U++ Application
Goto Forum:
  


Current Time: Thu Apr 18 03:35:25 CEST 2024

Total time taken to generate the page: 0.03897 seconds