Video Events Audio CD-ROM Threads

Multi-threaded Programming

SDL provides functions for creating threads and binary semphores (mutexes).

In general, you must be very aware of concurrency and data integrity issues when writing multi-threaded programs. Some good guidelines include:

  • Don't call SDL video/event functions from separate threads
  • Don't use any library functions in separate threads
  • Don't perform any memory management in separate threads
  • Lock global variables which may be accessed by multiple threads
  • Never terminate threads, always set a flag and wait for them to quit
  • Think very carefully about all possible ways your code may interact

Without any further ado:

extern SDL_Thread *SDL_CreateThread(int (*fn)(void *), void *data);

Defined in SDL_thread.h

SDL_CreateThread() creates a new thread of execution that shares all of its parent's global memory, signal handlers, file descriptors, etc, and runs the function 'fn' passed the void pointer 'data'. The thread quits when this function returns.

extern Uint32 SDL_ThreadID(void);

Get the 32-bit thread identifier for the current thread

extern void SDL_WaitThread(SDL_Thread *thread, int *status);

Defined in SDL_thread.h

Wait for a thread to finish (timeouts are not supported).
The return code for the thread function is placed in the area pointed to by 'status', if 'status' is not NULL.

extern void SDL_KillThread(SDL_Thread *thread);

Defined in SDL_thread.h

SDL_KillThread() gracelessly terminates the thread associated with 'thread'. If possible, you should use some other form of IPC to signal the thread to quit.

extern SDL_mutex *SDL_CreateMutex(void);

Defined in SDL_mutex.h

Returns a new mutex, initially unlocked, or NULL on error.

extern int SDL_mutexP(SDL_mutex *mutex);

Defined in SDL_mutex.h

Locks a mutex, returning 0, or -1 on error.

extern int SDL_mutexV(SDL_mutex *mutex);

Defined in SDL_mutex.h

Unlocks a mutex, returning 0, or -1 on error.

extern void SDL_DestroyMutex(SDL_mutex *mutex);

Defined in SDL_mutex.h

Destroys an existing mutex. Subsequent calls to lock or unlock the mutex will fail.