Click here to Skip to main content
13,739,613 members
Click here to Skip to main content

Stats

87.7K views
1.7K downloads
49 bookmarked
Posted 19 Apr 2011
Licenced CPOL

Spin Lock in C++

, 9 May 2011
A spin lock implementation which can be used for general purpose locking.
#ifndef __LOCKFREEQUEUE_IMPL__

#define __LOCKFREEQUEUE_IMPL__

#include <iostream>
#include <deque>
#include "ScopedLock.h"

using namespace std;

namespace LockFree
{

	template<class T>
	class tLockFreeQueue
	{
	public:
		tLockFreeQueue(){}

		void enqueue(T t)
		{
			tScopedLock oSpinLock(m_LockObj);
			m_LockFreeQueue.push_front(t);
		}
	
		T dequeue()
		{
			tScopedLock oSpinLock(m_LockObj);
			if(size() == 0)
				throw std::out_of_range("out of range");

			T LastElement = m_LockFreeQueue.back();
			m_LockFreeQueue.pop_back(T);
			return LastElement; 
		}

		unsigned int size() const
		{
			return m_LockFreeQueue.size();
		}

		void eraseAll()
		{
			tScopedLock oSpinLock(m_LockObj);
			m_LockFreeQueue.clear();
		}

	public:
		virtual ~tLockFreeQueue() 
		{}

	private:
		deque<T> m_LockFreeQueue;
		tSpinLock m_LockObj;

	};
};


#endif // __LOCKFREEQUEUE_IMPL__

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

sameer_87
Technical Lead Thomson Reuters Ltd, London
United Kingdom United Kingdom
Studied MSc Network and Parallel computing from Reading University, UK. I was always interested in IT. Previously worked in Network-Security, Games Development, Satellite Communications and now in Financial Services industry. After work, usually time spent with my son. Love playing cricket, badminton - though not happening much on sports these days. OK, enough about me.

Email: sameer_87@hotmail.com

You may also be interested in...

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.180920.1 | Last Updated 9 May 2011
Article Copyright 2011 by sameer_87
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid