foxygit / doom Log in
commit 40ca9e8297ae8638c638f33b6ef5393ee88c7056
Author:     Simon Howard <fraggle@gmail.com>
AuthorDate: Tue Jun 2 00:36:52 2009 +0000
Commit:     Simon Howard <fraggle@gmail.com>
CommitDate: Tue Jun 2 00:36:52 2009 +0000

    Fix crash due to timer thread starting before resources allocated.

    Subversion-branch: /branches/opl-branch
    Subversion-revision: 1540
---
 opl/opl_timer.c | 27 ++++++++++++++++++++++-----
 1 file changed, 22 insertions(+), 5 deletions(-)

diff --git a/opl/opl_timer.c b/opl/opl_timer.c
index 519dbbd9..62ffbd37 100644
--- a/opl/opl_timer.c
+++ b/opl/opl_timer.c
@@ -149,19 +149,34 @@ static int ThreadFunction(void *unused)
     return 0;
 }

-int OPL_Timer_StartThread(void)
+static void InitResources(void)
 {
-    timer_thread_state = THREAD_STATE_RUNNING;
-    timer_thread = SDL_CreateThread(ThreadFunction, NULL);
-    timer_mutex = SDL_CreateMutex();
-
     callback_queue = OPL_Queue_Create();
+    timer_mutex = SDL_CreateMutex();
     callback_queue_mutex = SDL_CreateMutex();
+}
+
+static void FreeResources(void)
+{
+    OPL_Queue_Destroy(callback_queue);
+    SDL_DestroyMutex(callback_queue_mutex);
+    SDL_DestroyMutex(timer_mutex);
+}
+
+int OPL_Timer_StartThread(void)
+{
+    InitResources();
+
+    timer_thread_state = THREAD_STATE_RUNNING;
     current_time = SDL_GetTicks();

+    timer_thread = SDL_CreateThread(ThreadFunction, NULL);
+
     if (timer_thread == NULL)
     {
         timer_thread_state = THREAD_STATE_STOPPED;
+        FreeResources();
+
         return 0;
     }

@@ -176,6 +191,8 @@ void OPL_Timer_StopThread(void)
     {
         SDL_Delay(1);
     }
+
+    FreeResources();
 }

 void OPL_Timer_SetCallback(unsigned int ms, opl_callback_t callback, void *data)