Raised This Month: $ Target: $400
 0% 

Thread safe stack?


Post New Thread Reply   
 
Thread Tools Display Modes
Author Message
devicenull
Veteran Member
Join Date: Mar 2004
Location: CT
Old 06-19-2006 , 20:50   Thread safe stack?
Reply With Quote #1

Code:
/*=================Last Connected======================
*	Copyright (C) 2005-2006 Brian "devicenull" Rak
*	License: zlib/libpng
*	$Id: safeStack.h 23 2006-06-16 18:33:22Z  $
=====================================================*/

#include "sh_stack.h"
#include "pthread.h"

template <class T> class safeStack
{
public:
	void init()
	{
		pthread_mutex_init(&mSafe,NULL);
	}
	void destroy()
	{
		pthread_mutex_lock(&mSafe);
		pthread_mutex_destroy(&mSafe);
	}
	void push(T newItem)
	{
		pthread_mutex_lock(&mSafe);
		sStack.push(newItem);
		pthread_mutex_unlock(&mSafe);
	}
	T& pop()
	{
		pthread_mutex_lock(&mSafe);
		T &temp = sStack.front();
		sStack.pop();
		pthread_mutex_unlock(&mSafe);
		return temp;
	}
	int count()
	{
		pthread_mutex_lock(&mSafe);
		int temp = sStack.size();
		pthread_mutex_unlock(&mSafe);
		return temp;
	}


private:
	SourceHook::CStack<T> sStack;
	pthread_mutex_t mSafe;
};
My question: Is this a good way of doing it? I only need push, pop, and count, so those are the only one's I've implemented. I don't initalize the mutex in the constructor because I have to initalize the pthread library before I can call that, and I've set it up to not use a pointer to the safeStack object.
__________________
Various bits of semi-useful code in a bunch of languages: http://code.devicenull.org/
devicenull is offline
BAILOPAN
Join Date: Jan 2004
Old 06-21-2006 , 14:35  
Reply With Quote #2

Yes, that works. Locking/unlocking mutexes is expensive. If you do a lot of operations in a row, you might want to introduce two new member functions: lock() and unlock().
__________________
egg
BAILOPAN is offline
kormonautti
Junior Member
Join Date: Apr 2006
Old 06-24-2006 , 20:02   Re: Thread safe stack?
Reply With Quote #3

You should use the constructor and destructor. Now there is a possibility to resource leaks and that is not a good idea. Also remember to check return values of pthread functions. This is from the pthread man:
Quote:
The pthread_mutex_destroy function returns the following
error code on error:

EBUSY the mutex is currently locked.
kormonautti is offline
Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 21:48.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode