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