Advertisement

Class members loose their values????

Started by August 23, 2000 09:43 PM
3 comments, last by gimp 24 years, 4 months ago
I'm writing a threadsafe wrapper class around an STL deque. The problem in the following code seems to be that the Mutex pointer looses it's value and is somehow reset to NULL. (I hope this isn't a silly question)
    
//Thread safe Queue Class

class CQueue
{
public:
	CQueue()
	{
		Mutex = SDL_CreateMutex();
	}

	~CQueue()
	{
		SDL_DestroyMutex(Mutex);
	}

	void Put(byte *p)
	{
		SDL_mutexP(this->Mutex);

		itsMessageQueue.push_back(p);

		SDL_mutexV(Mutex);
	}

	byte *Get(void)
	{
		SDL_mutexP(Mutex);
		
		byte *tempMessage=NULL;

		tempMessage = itsMessageQueue.front();
		itsMessageQueue.pop_front();

		SDL_mutexV(Mutex);

		return tempMessage;
	}

	const Boolean IsEmpty(void) const
	{
		SDL_mutexP(Mutex);

		Boolean ret;
		ret = itsMessageQueue.empty();

		SDL_mutexV(Mutex);

		return ret;
	} 


private:
	typedef deque<byte*> MessageQueueDeque;
	MessageQueueDeque itsMessageQueue;

	SDL_mutex *Mutex;
};
    
Many thanks gimp Edited by - gimp on 8/23/00 9:47:10 PM
Chris Brodie
mutexes/semaphores usually need to be global or static, after all they''re shared.

Advertisement
I have no idea, since I''m not familiar with that library''s functionality. I see no reason why the pointer should be cleared to NULL, unless it''s part of the library''s way of telling you the actual MUTEX resource was somehow nuked (unlikely...). Are you -sure- that SDL_CreateMutex() is actually returning a pointer and not NULL in the first place? Also, why do you mix "this->Mutex" and "Mutex" in the code? They both mean exactly the same thing, just that the first syntax is redundant.
Looking over the SDL docs it looks like Kylotan is correct, check for null when you create the mutex. Also CQueue needs to be global (or not exit scope before any threads use it). try adding a message/breakpoint to the dtor to see if it''s called unexpectedly.
The mutex should NOT be static or global. If you have two queues, you would only be able to access one at a time even though the two queues have nothing to do with each other.

The destructor cannot be causing the problem of the Mutex being NULL, because it''s only called immediately before the CQueue is destroyed.

Either SDL_CreateMutex doesn''t return a value, as some have guessed at here, or you have a wild pointer somewhere else in your program that is overwriting your class data.

Best of luck.

This topic is closed to new replies.

Advertisement