src/thread/SDL_thread.c
author Sam Lantinga <slouken@libsdl.org>
Sun, 04 Jan 2004 16:49:27 +0000
changeset 769 b8d311d90021
parent 397 283d348cb624
child 1190 173c063d4f55
permissions -rw-r--r--
Updated copyright information for 2004 (Happy New Year!)
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997-2004 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 	retval = 0;
    56 	/* Set the thread lock creation flag so that we can reuse an
    57 	   existing lock on the system - since this mutex never gets
    58 	   destroyed (see SDL_ThreadsQuit()), we want to reuse it.
    59 	*/
    60 	_creating_thread_lock = 1;
    61 	thread_lock = SDL_CreateMutex();
    62 	_creating_thread_lock = 0;
    63 	if ( thread_lock == NULL ) {
    64 		retval = -1;
    65 	}
    66 	return(retval);
    67 }
    68 
    69 /* This should never be called...
    70    If this is called by SDL_Quit(), we don't know whether or not we should
    71    clean up threads here.  If any threads are still running after this call,
    72    they will no longer have access to any per-thread data.
    73  */
    74 void SDL_ThreadsQuit()
    75 {
    76 	SDL_mutex *mutex;
    77 
    78 	mutex = thread_lock;
    79 	thread_lock = NULL;
    80 	if ( mutex != NULL ) {
    81 		SDL_DestroyMutex(mutex);
    82 	}
    83 }
    84 
    85 /* Routines for manipulating the thread list */
    86 static void SDL_AddThread(SDL_Thread *thread)
    87 {
    88 	SDL_Thread **threads;
    89 
    90 	/* WARNING:
    91 	   If the very first threads are created simultaneously, then
    92 	   there could be a race condition causing memory corruption.
    93 	   In practice, this isn't a problem because by definition there
    94 	   is only one thread running the first time this is called.
    95 	*/
    96 	if ( thread_lock == NULL ) {
    97 		if ( SDL_ThreadsInit() < 0 ) {
    98 			return;
    99 		}
   100 	}
   101 	SDL_mutexP(thread_lock);
   102 
   103 	/* Expand the list of threads, if necessary */
   104 #ifdef DEBUG_THREADS
   105 	printf("Adding thread (%d already - %d max)\n",
   106 			SDL_numthreads, SDL_maxthreads);
   107 #endif
   108 	if ( SDL_numthreads == SDL_maxthreads ) {
   109 		threads=(SDL_Thread **)malloc((SDL_maxthreads+ARRAY_CHUNKSIZE)*
   110 		                              (sizeof *threads));
   111 		if ( threads == NULL ) {
   112 			SDL_OutOfMemory();
   113 			goto done;
   114 		}
   115 		memcpy(threads, SDL_Threads, SDL_numthreads*(sizeof *threads));
   116 		SDL_maxthreads += ARRAY_CHUNKSIZE;
   117 		if ( SDL_Threads ) {
   118 			free(SDL_Threads);
   119 		}
   120 		SDL_Threads = threads;
   121 	}
   122 	SDL_Threads[SDL_numthreads++] = thread;
   123 done:
   124 	SDL_mutexV(thread_lock);
   125 }
   126 
   127 static void SDL_DelThread(SDL_Thread *thread)
   128 {
   129 	int i;
   130 
   131 	if ( thread_lock ) {
   132 		SDL_mutexP(thread_lock);
   133 		for ( i=0; i<SDL_numthreads; ++i ) {
   134 			if ( thread == SDL_Threads[i] ) {
   135 				break;
   136 			}
   137 		}
   138 		if ( i < SDL_numthreads ) {
   139 			if ( --SDL_numthreads > 0 ) {
   140 				while ( i < SDL_numthreads ) {
   141 					SDL_Threads[i] = SDL_Threads[i+1];
   142 					++i;
   143 				}
   144 			} else {
   145 				SDL_maxthreads = 0;
   146 				free(SDL_Threads);
   147 				SDL_Threads = NULL;
   148 			}
   149 #ifdef DEBUG_THREADS
   150 			printf("Deleting thread (%d left - %d max)\n",
   151 					SDL_numthreads, SDL_maxthreads);
   152 #endif
   153 		}
   154 		SDL_mutexV(thread_lock);
   155 	}
   156 }
   157 
   158 /* The default (non-thread-safe) global error variable */
   159 static SDL_error SDL_global_error;
   160 
   161 /* Routine to get the thread-specific error variable */
   162 SDL_error *SDL_GetErrBuf(void)
   163 {
   164 	SDL_error *errbuf;
   165 
   166 	errbuf = &SDL_global_error;
   167 	if ( SDL_Threads ) {
   168 		int i;
   169 		Uint32 this_thread;
   170 
   171 		this_thread = SDL_ThreadID();
   172 		SDL_mutexP(thread_lock);
   173 		for ( i=0; i<SDL_numthreads; ++i ) {
   174 			if ( this_thread == SDL_Threads[i]->threadid ) {
   175 				errbuf = &SDL_Threads[i]->errbuf;
   176 				break;
   177 			}
   178 		}
   179 		SDL_mutexV(thread_lock);
   180 	}
   181 	return(errbuf);
   182 }
   183 
   184 
   185 /* Arguments and callback to setup and run the user thread function */
   186 typedef struct {
   187 	int (*func)(void *);
   188 	void *data;
   189 	SDL_Thread *info;
   190 	SDL_sem *wait;
   191 } thread_args;
   192 
   193 void SDL_RunThread(void *data)
   194 {
   195 	thread_args *args;
   196 	int (*userfunc)(void *);
   197 	void *userdata;
   198 	int *statusloc;
   199 
   200 	/* Perform any system-dependent setup
   201 	   - this function cannot fail, and cannot use SDL_SetError()
   202 	 */
   203 	SDL_SYS_SetupThread();
   204 
   205 	/* Get the thread id */
   206 	args = (thread_args *)data;
   207 	args->info->threadid = SDL_ThreadID();
   208 
   209 	/* Figure out what function to run */
   210 	userfunc = args->func;
   211 	userdata = args->data;
   212 	statusloc = &args->info->status;
   213 
   214 	/* Wake up the parent thread */
   215 	SDL_SemPost(args->wait);
   216 
   217 	/* Run the function */
   218 	*statusloc = userfunc(userdata);
   219 }
   220 
   221 SDL_Thread *SDL_CreateThread(int (*fn)(void *), void *data)
   222 {
   223 	SDL_Thread *thread;
   224 	thread_args *args;
   225 	int ret;
   226 
   227 	/* Allocate memory for the thread info structure */
   228 	thread = (SDL_Thread *)malloc(sizeof(*thread));
   229 	if ( thread == NULL ) {
   230 		SDL_OutOfMemory();
   231 		return(NULL);
   232 	}
   233 	memset(thread, 0, (sizeof *thread));
   234 	thread->status = -1;
   235 
   236 	/* Set up the arguments for the thread */
   237 	args = (thread_args *)malloc(sizeof(*args));
   238 	if ( args == NULL ) {
   239 		SDL_OutOfMemory();
   240 		free(thread);
   241 		return(NULL);
   242 	}
   243 	args->func = fn;
   244 	args->data = data;
   245 	args->info = thread;
   246 	args->wait = SDL_CreateSemaphore(0);
   247 	if ( args->wait == NULL ) {
   248 		free(thread);
   249 		free(args);
   250 		return(NULL);
   251 	}
   252 
   253 	/* Add the thread to the list of available threads */
   254 	SDL_AddThread(thread);
   255 
   256 	/* Create the thread and go! */
   257 	ret = SDL_SYS_CreateThread(thread, args);
   258 	if ( ret >= 0 ) {
   259 		/* Wait for the thread function to use arguments */
   260 		SDL_SemWait(args->wait);
   261 	} else {
   262 		/* Oops, failed.  Gotta free everything */
   263 		SDL_DelThread(thread);
   264 		free(thread);
   265 		thread = NULL;
   266 	}
   267 	SDL_DestroySemaphore(args->wait);
   268 	free(args);
   269 
   270 	/* Everything is running now */
   271 	return(thread);
   272 }
   273 
   274 void SDL_WaitThread(SDL_Thread *thread, int *status)
   275 {
   276 	if ( thread ) {
   277 		SDL_SYS_WaitThread(thread);
   278 		if ( status ) {
   279 			*status = thread->status;
   280 		}
   281 		SDL_DelThread(thread);
   282 		free(thread);
   283 	}
   284 }
   285 
   286 Uint32 SDL_GetThreadID(SDL_Thread *thread)
   287 {
   288 	Uint32 id;
   289 
   290 	if ( thread ) {
   291 		id = thread->threadid;
   292 	} else {
   293 		id = SDL_ThreadID();
   294 	}
   295 	return(id);
   296 }
   297 
   298 void SDL_KillThread(SDL_Thread *thread)
   299 {
   300 	if ( thread ) {
   301 		SDL_SYS_KillThread(thread);
   302 		SDL_WaitThread(thread, NULL);
   303 	}
   304 }
   305