[SDL] Thread and conditional variable example

Tyler Montbriand tsm at accesscomm.ca
Sat Nov 15 15:53:01 PST 2003

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];

    fprintf(stderr,"Couldn't init SDL\n");


  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_CondBroadcast(launch); /* move zig! */

    for(n=0; n<zigs; n++)
      if(t[n]!=NULL) SDL_WaitThread(t[n],NULL);

    fprintf(stderr,"main] You know what you doing\n");
    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);

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_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);


More information about the SDL mailing list