1 /*
2 	OpenLieroX
3 
4 	Mutex wrapper implementation
5 
6 	created 10-02-2009 by Karel Petranek
7 	code under LGPL
8 */
9 
10 #include <SDL_thread.h>
11 
12 #include "Mutex.h"
13 #include "Debug.h"
14 
15 #ifdef DEBUG
16 
17 // TODO: This code is threadsafe and thus not very usable.
18 
19 /*
20 Mutex::Mutex()
21 {
22 	m_mutex = SDL_CreateMutex();
23 	m_lockedThread = INVALID_THREAD_ID;
24 }
25 
26 Mutex::~Mutex()
27 {
28 	SDL_DestroyMutex(m_mutex);
29 
30 	// If there's a thread set, we're destroying a locked mutex
31 	if (m_lockedThread != INVALID_THREAD_ID)  {
32 		errors << "Destroyed a locked mutex" << endl;
33 		assert(false);
34 	}
35 }
36 
37 void Mutex::lock()
38 {
39 	// Get the current thread ID, if the thread ID is the same as the one already set, we've called
40 	// lock() twice from the same thread
41 	Uint32 id = SDL_ThreadID();
42 	if (m_lockedThread == id)  {
43 		errors << "Called mutex lock twice from the same thread, this will cause a deadlock" << endl;
44 		assert(false);
45 	}
46 
47 	SDL_LockMutex(m_mutex);
48 	m_lockedThread = id;  // We hold the lock now
49 }
50 
51 void Mutex::unlock()
52 {
53 	// Make sure the mutex is released from the same thread it was locked in
54 	if (m_lockedThread != SDL_ThreadID())  {
55 		errors << "Releasing the mutex in other thread than locking it, this will cause a deadlock" << endl;
56 		assert(false);
57 	}
58 	m_lockedThread = INVALID_THREAD_ID;  // Lock released
59 
60 	SDL_UnlockMutex(m_mutex);
61 }
62 */
63 
64 // Testing stuff
65 /*
66 int thread_release_main(void *m)
67 {
68 	Mutex *mutex = (Mutex *)m;
69 	mutex->lock();
70 	return 0;
71 }
72 
73 
74 void Mutex::test()
75 {
76 	Mutex mtx;
77 
78 	// Lock in one thread and unlock in another one
79 	SDL_Thread *rel = SDL_CreateThread(thread_release_main, &mtx);
80 	SDL_WaitThread(rel, NULL);
81 	mtx.unlock();
82 
83 	// Deadlock
84 	mtx.lock();
85 	mtx.lock();
86 
87 	//mtx.lock();  // Lock and then destroy
88 }
89 */
90 
91 #endif
92