1 2 /* Simple test of the SDL semaphore code */ 3 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <signal.h> 7 8 #include "SDL.h" 9 #include "SDL_thread.h" 10 11 #define NUM_THREADS 10 12 13 static SDL_sem *sem; 14 int alive = 1; 15 16 int SDLCALL ThreadFunc(void *data) 17 { 18 int threadnum = (int)(uintptr_t)data; 19 while ( alive ) { 20 SDL_SemWait(sem); 21 fprintf(stderr, "Thread number %d has got the semaphore (value = %d)!\n", threadnum, SDL_SemValue(sem)); 22 SDL_Delay(200); 23 SDL_SemPost(sem); 24 fprintf(stderr, "Thread number %d has released the semaphore (value = %d)!\n", threadnum, SDL_SemValue(sem)); 25 SDL_Delay(1); /* For the scheduler */ 26 } 27 printf("Thread number %d exiting.\n", threadnum); 28 return 0; 29 } 30 31 static void killed(int sig) 32 { 33 alive = 0; 34 } 35 36 static void TestWaitTimeout(void) 37 { 38 Uint32 start_ticks; 39 Uint32 end_ticks; 40 Uint32 duration; 41 42 sem = SDL_CreateSemaphore(0); 43 printf("Waiting 2 seconds on semaphore\n"); 44 45 start_ticks = SDL_GetTicks(); 46 SDL_SemWaitTimeout(sem, 2000); 47 end_ticks = SDL_GetTicks(); 48 49 duration = end_ticks - start_ticks; 50 51 /* Accept a little offset in the effective wait */ 52 if (duration > 1900 && duration < 2050) 53 printf("Wait done.\n"); 54 else 55 fprintf(stderr, "Wait took %d milliseconds\n", duration); 56 } 57 58 int main(int argc, char **argv) 59 { 60 SDL_Thread *threads[NUM_THREADS]; 61 uintptr_t i; 62 int init_sem; 63 64 if(argc < 2) { 65 fprintf(stderr,"Usage: %s init_value\n", argv[0]); 66 return(1); 67 } 68 69 /* Load the SDL library */ 70 if ( SDL_Init(0) < 0 ) { 71 fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError()); 72 return(1); 73 } 74 signal(SIGTERM, killed); 75 signal(SIGINT, killed); 76 77 init_sem = atoi(argv[1]); 78 sem = SDL_CreateSemaphore(init_sem); 79 80 printf("Running %d threads, semaphore value = %d\n", NUM_THREADS, init_sem); 81 /* Create all the threads */ 82 for( i = 0; i < NUM_THREADS; ++i ) { 83 threads[i] = SDL_CreateThread(ThreadFunc, (void*)i); 84 } 85 86 /* Wait 10 seconds */ 87 SDL_Delay(10 * 1000); 88 89 /* Wait for all threads to finish */ 90 printf("Waiting for threads to finish\n"); 91 alive = 0; 92 for( i = 0; i < NUM_THREADS; ++i ) { 93 SDL_WaitThread(threads[i], NULL); 94 } 95 printf("Finished waiting for threads\n"); 96 97 SDL_DestroySemaphore(sem); 98 99 TestWaitTimeout(); 100 101 SDL_Quit(); 102 return(0); 103 } 104