I think I’ve managed to hammer out how conditional variables are supposed to
be used in SDL… it seems to work. does anyone see anything fundamentally
wrong with it?
/**
- Demonstration of mutexes, semaphores, and conditional variables
- in SDL, by Tyler Montbriand, 2003.*
- This code is freeware. Do whatever you want with it.
*/
#include <SDL/SDL.h>
#include <SDL/SDL_thread.h>
#include <stdlib.h>
SDL_sem *sem=NULL;
SDL_mutex *mutex=NULL;
SDL_cond *launch=NULL;
/* Function that will be called by threads */
int zig(void *t);
int main(int argc, char *argv[])
{
int n;
const int zigs=4;
SDL_Thread *t[zigs];
if(SDL_Init(SDL_INIT_EVENTTHREAD)<0)
{
fprintf(stderr,“Couldn’t init SDL\n”);
return(1);
}
mutex=SDL_CreateMutex();
sem=SDL_CreateSemaphore(0);
launch=SDL_CreateCond();
if(mutex && launch && sem)
{
fprintf(stderr,“main] Take off every zig!\n”);
for(n=0; n<zigs; n++)
{
t[n]=SDL_CreateThread(zig,(void *)n);
if(t[n]!=NULL) SDL_SemWait(sem); /* wait until zig has locked mutex */
}
fprintf(stderr,"main] MOVE ZIG!\n");
SDL_mutexP(mutex);
SDL_CondBroadcast(launch); /* move zig! */
SDL_mutexV(mutex);
for(n=0; n<zigs; n++)
if(t[n]!=NULL) SDL_WaitThread(t[n],NULL);
fprintf(stderr,"main] You know what you doing\n");
}
else
fprintf(stderr,“Couldn’t create signalling devices\n”);
if(sem!=NULL) SDL_DestroySemaphore(sem);
if(mutex!=NULL) SDL_DestroyMutex(mutex);
if(launch!=NULL) SDL_DestroyCond(launch);
return(0);
}
int zig(void *t)
{
if((mutex==NULL)||(launch==NULL)||(sem==NULL)) return(-1);
SDL_mutexP(mutex); /* Need to lock mutex before calling SDL_CondWait */
{
fprintf(stderr,"%02d] Zig ready for launch.\n",t);
SDL_SemPost(sem); /* Notify main that we have locked mutex */
SDL_CondWait(launch,mutex); /* Wait until main triggers all threads */
/* Critical section - no other threads are running in this part */
{
fprintf(stderr,"%02d] Zig launched!\n",t);
SDL_Delay(100);
}
}
SDL_mutexV(mutex); /* exit critical section - let next zig launch */
SDL_Delay(1000); /* Can happen the same time as other threads */
fprintf(stderr,"%02d] Zig out of fuel\n",t);
return(0);
}