src/thread/SDL_thread.c
author Sam Lantinga
Thu, 11 Apr 2002 21:08:44 +0000
changeset 340 b9f1ce709960
parent 329 1d74ddc90cb2
child 397 283d348cb624
permissions -rw-r--r--
Fixed a minor memory leak in the SDL thread subsystem
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002  Sam Lantinga
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Library General Public
     7     License as published by the Free Software Foundation; either
     8     version 2 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Library General Public License for more details.
    14 
    15     You should have received a copy of the GNU Library General Public
    16     License along with this library; if not, write to the Free
    17     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    18 
    19     Sam Lantinga
    20     slouken@libsdl.org
    21 */
    22 
    23 #ifdef SAVE_RCSID
    24 static char rcsid =
    25  "@(#) $Id$";
    26 #endif
    27 
    28 /* System independent thread management routines for SDL */
    29 
    30 #include <stdio.h>
    31 #include <stdlib.h>
    32 #include <string.h>
    33 
    34 #include "SDL_error.h"
    35 #include "SDL_mutex.h"
    36 #include "SDL_thread.h"
    37 #include "SDL_thread_c.h"
    38 #include "SDL_systhread.h"
    39 
    40 #define ARRAY_CHUNKSIZE	32
    41 /* The array of threads currently active in the application
    42    (except the main thread)
    43    The manipulation of an array here is safer than using a linked list.
    44 */
    45 static int SDL_maxthreads = 0;
    46 static int SDL_numthreads = 0;
    47 static SDL_Thread **SDL_Threads = NULL;
    48 static SDL_mutex *thread_lock = NULL;
    49 int _creating_thread_lock = 0;
    50 
    51 int SDL_ThreadsInit(void)
    52 {
    53 	int retval;
    54 
    55 #ifdef ENABLE_PTH
    56 	if (!pth_init()) {
    57 		return -1;
    58 	}
    59 #endif
    60 
    61 	retval = 0;
    62 	/* Set the thread lock creation flag so that we can reuse an
    63 	   existing lock on the system - since this mutex never gets
    64 	   destroyed (see SDL_ThreadsQuit()), we want to reuse it.
    65 	*/
    66 	_creating_thread_lock = 1;
    67 	thread_lock = SDL_CreateMutex();
    68 	_creating_thread_lock = 0;
    69 	if ( thread_lock == NULL ) {
    70 		retval = -1;
    71 	}
    72 	return(retval);
    73 }
    74 
    75 /* This should never be called...
    76    If this is called by SDL_Quit(), we don't know whether or not we should
    77    clean up threads here.  If any threads are still running after this call,
    78    they will no longer have access to any per-thread data.
    79  */
    80 void SDL_ThreadsQuit()
    81 {
    82 	SDL_mutex *mutex;
    83 
    84 	mutex = thread_lock;
    85 	thread_lock = NULL;
    86 	if ( mutex != NULL ) {
    87 		SDL_DestroyMutex(mutex);
    88 	}
    89 
    90 #ifdef ENABLE_PTH
    91 	pth_kill();
    92 #endif
    93 }
    94 
    95 /* Routines for manipulating the thread list */
    96 static void SDL_AddThread(SDL_Thread *thread)
    97 {
    98 	SDL_Thread **threads;
    99 
   100 	/* WARNING:
   101 	   If the very first threads are created simultaneously, then
   102 	   there could be a race condition causing memory corruption.
   103 	   In practice, this isn't a problem because by definition there
   104 	   is only one thread running the first time this is called.
   105 	*/
   106 	if ( thread_lock == NULL ) {
   107 		if ( SDL_ThreadsInit() < 0 ) {
   108 			return;
   109 		}
   110 	}
   111 	SDL_mutexP(thread_lock);
   112 
   113 	/* Expand the list of threads, if necessary */
   114 #ifdef DEBUG_THREADS
   115 	printf("Adding thread (%d already - %d max)\n",
   116 			SDL_numthreads, SDL_maxthreads);
   117 #endif
   118 	if ( SDL_numthreads == SDL_maxthreads ) {
   119 		threads=(SDL_Thread **)malloc((SDL_maxthreads+ARRAY_CHUNKSIZE)*
   120 		                              (sizeof *threads));
   121 		if ( threads == NULL ) {
   122 			SDL_OutOfMemory();
   123 			goto done;
   124 		}
   125 		memcpy(threads, SDL_Threads, SDL_numthreads*(sizeof *threads));
   126 		SDL_maxthreads += ARRAY_CHUNKSIZE;
   127 		if ( SDL_Threads ) {
   128 			free(SDL_Threads);
   129 		}
   130 		SDL_Threads = threads;
   131 	}
   132 	SDL_Threads[SDL_numthreads++] = thread;
   133 done:
   134 	SDL_mutexV(thread_lock);
   135 }
   136 
   137 static void SDL_DelThread(SDL_Thread *thread)
   138 {
   139 	int i;
   140 
   141 	if ( thread_lock ) {
   142 		SDL_mutexP(thread_lock);
   143 		for ( i=0; i<SDL_numthreads; ++i ) {
   144 			if ( thread == SDL_Threads[i] ) {
   145 				break;
   146 			}
   147 		}
   148 		if ( i < SDL_numthreads ) {
   149 			if ( --SDL_numthreads > 0 ) {
   150 				while ( i < SDL_numthreads ) {
   151 					SDL_Threads[i] = SDL_Threads[i+1];
   152 					++i;
   153 				}
   154 			} else {
   155 				SDL_maxthreads = 0;
   156 				free(SDL_Threads);
   157 				SDL_Threads = NULL;
   158 			}
   159 #ifdef DEBUG_THREADS
   160 			printf("Deleting thread (%d left - %d max)\n",
   161 					SDL_numthreads, SDL_maxthreads);
   162 #endif
   163 		}
   164 		SDL_mutexV(thread_lock);
   165 	}
   166 }
   167 
   168 /* The default (non-thread-safe) global error variable */
   169 static SDL_error SDL_global_error;
   170 
   171 /* Routine to get the thread-specific error variable */
   172 SDL_error *SDL_GetErrBuf(void)
   173 {
   174 	SDL_error *errbuf;
   175 
   176 	errbuf = &SDL_global_error;
   177 	if ( SDL_Threads ) {
   178 		int i;
   179 		Uint32 this_thread;
   180 
   181 		this_thread = SDL_ThreadID();
   182 		SDL_mutexP(thread_lock);
   183 		for ( i=0; i<SDL_numthreads; ++i ) {
   184 			if ( this_thread == SDL_Threads[i]->threadid ) {
   185 				errbuf = &SDL_Threads[i]->errbuf;
   186 				break;
   187 			}
   188 		}
   189 		SDL_mutexV(thread_lock);
   190 	}
   191 	return(errbuf);
   192 }
   193 
   194 
   195 /* Arguments and callback to setup and run the user thread function */
   196 typedef struct {
   197 	int (*func)(void *);
   198 	void *data;
   199 	SDL_Thread *info;
   200 	SDL_sem *wait;
   201 } thread_args;
   202 
   203 void SDL_RunThread(void *data)
   204 {
   205 	thread_args *args;
   206 	int (*userfunc)(void *);
   207 	void *userdata;
   208 	int *statusloc;
   209 
   210 	/* Perform any system-dependent setup
   211 	   - this function cannot fail, and cannot use SDL_SetError()
   212 	 */
   213 	SDL_SYS_SetupThread();
   214 
   215 	/* Get the thread id */
   216 	args = (thread_args *)data;
   217 	args->info->threadid = SDL_ThreadID();
   218 
   219 	/* Figure out what function to run */
   220 	userfunc = args->func;
   221 	userdata = args->data;
   222 	statusloc = &args->info->status;
   223 
   224 	/* Wake up the parent thread */
   225 	SDL_SemPost(args->wait);
   226 
   227 	/* Run the function */
   228 	*statusloc = userfunc(userdata);
   229 }
   230 
   231 SDL_Thread *SDL_CreateThread(int (*fn)(void *), void *data)
   232 {
   233 	SDL_Thread *thread;
   234 	thread_args *args;
   235 	int ret;
   236 
   237 	/* Allocate memory for the thread info structure */
   238 	thread = (SDL_Thread *)malloc(sizeof(*thread));
   239 	if ( thread == NULL ) {
   240 		SDL_OutOfMemory();
   241 		return(NULL);
   242 	}
   243 	memset(thread, 0, (sizeof *thread));
   244 	thread->status = -1;
   245 
   246 	/* Set up the arguments for the thread */
   247 	args = (thread_args *)malloc(sizeof(*args));
   248 	if ( args == NULL ) {
   249 		SDL_OutOfMemory();
   250 		free(thread);
   251 		return(NULL);
   252 	}
   253 	args->func = fn;
   254 	args->data = data;
   255 	args->info = thread;
   256 	args->wait = SDL_CreateSemaphore(0);
   257 	if ( args->wait == NULL ) {
   258 		free(thread);
   259 		free(args);
   260 		return(NULL);
   261 	}
   262 
   263 	/* Add the thread to the list of available threads */
   264 	SDL_AddThread(thread);
   265 
   266 	/* Create the thread and go! */
   267 	ret = SDL_SYS_CreateThread(thread, args);
   268 	if ( ret >= 0 ) {
   269 		/* Wait for the thread function to use arguments */
   270 		SDL_SemWait(args->wait);
   271 	} else {
   272 		/* Oops, failed.  Gotta free everything */
   273 		SDL_DelThread(thread);
   274 		free(thread);
   275 		thread = NULL;
   276 	}
   277 	SDL_DestroySemaphore(args->wait);
   278 	free(args);
   279 
   280 	/* Everything is running now */
   281 	return(thread);
   282 }
   283 
   284 void SDL_WaitThread(SDL_Thread *thread, int *status)
   285 {
   286 	if ( thread ) {
   287 		SDL_SYS_WaitThread(thread);
   288 		if ( status ) {
   289 			*status = thread->status;
   290 		}
   291 		SDL_DelThread(thread);
   292 		free(thread);
   293 	}
   294 }
   295 
   296 Uint32 SDL_GetThreadID(SDL_Thread *thread)
   297 {
   298 	Uint32 id;
   299 
   300 	if ( thread ) {
   301 		id = thread->threadid;
   302 	} else {
   303 		id = SDL_ThreadID();
   304 	}
   305 	return(id);
   306 }
   307 
   308 void SDL_KillThread(SDL_Thread *thread)
   309 {
   310 	if ( thread ) {
   311 		SDL_SYS_KillThread(thread);
   312 		SDL_WaitThread(thread, NULL);
   313 	}
   314 }
   315