I’ve dived into writing a multithreaded map server (actually a mini
geoinformatic engine) for my game and found existing documentation
on SDL threads quite scarce.
What’s there is at
I want to be sure that I understood the following right.
- When you create a mutex, you should put it into ‘public domain’ for
the threads (i.e. global var, for example), so that every thread has
access to it.
You can either do that or pass it around by itself or within some data
structure as the “data” portion of the SDL_CreateThread() call.
- The SDL_MutexP() and SDL_MutexV() are atomic.
No, they are not. They simply guarantee that only one thread can lock a
mutex. Unlocking a mutex should be done by the calling thread only. If
not, you are relying on undocumented, nonportable semantics as far as SDL
- The SDL_MutexP() returns 0 if mutex was unlocked and is now locked,
and -1 if mutex was locked, and remains locked (obviously by
some other thread)
SDL_mutexP() returns 0 if the mutex has now been locked and returns -1 on
error. This call blocks if the given mutex is locked by another thread.
The SDL_mutexP() call will return with a locked mutex only when the other
thread unlocks it. (There is currently no SDL_mutexTryP() or something
- The SDL_MutexV() returns 0 either if mutex was locked by this
thread and is now unlocked or mutex was unlocked and -1 if mutex was
locked by some other thread (and it remains locked)
The only correct semantics are for the thread that successfully locked a
mutex to call SDL_mutexV() to unlock it. In this case, SDL_mutexV() will
return 0 on successful unlock, -1 on error. You should be very careful
about trying to unlock a mutex. Your program should be written so a
thread knows it has a lock and will unlock it in due course.
- Each thread has its own local variables (in function supplied to
Everything visible up until the SDL_CreateThread() call is visible after
the call. From the point of thread creation on, a new thread has its own
stack which starts in the calling function.
For instance, global variables will be visible by a thread after calling
SDL_CreateThread(). Variables local to the function in the main thread
that makes the call can be passed as the “data” portion of
SDL_CreateThread() and become visible after the call. While the heap is
shared between threads, pointers to data in the heap follow the same rules
as automatic variables.
Last thing. SDL currently does not provide conditional variables. This
is a very important paradigm which is missing because of the difficulty in
creating a proper conditional variable in Win32. I’ve found an
implementation of pthreads for Win32 and am going to look through and see
if I can get some XP CVs working in SDL.
@Paul_BramanOn Mon, 31 Jan 2000, LxNT wrote: