test/testsem.c
author Sam Lantinga <slouken@libsdl.org>
Sun, 26 Feb 2006 05:02:14 +0000
changeset 1439 4d3bb026cd16
parent 1151 be9c9c8f6d53
child 1495 1dd8bf30a109
permissions -rw-r--r--
Fixed warnings in -pedantic mode
     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 ThreadFunc(void *data)
    17 {
    18 	while ( alive ) {
    19 		SDL_SemWait(sem);
    20 		fprintf(stderr, "Thread number %d has got the semaphore (value = %d)!\n", (int)data, SDL_SemValue(sem));
    21 		SDL_Delay(200);
    22 		SDL_SemPost(sem);
    23 		fprintf(stderr, "Thread number %d has released the semaphore (value = %d)!\n", (int)data, SDL_SemValue(sem));
    24 		SDL_Delay(1); /* For the scheduler */
    25 	}
    26 	printf("Thread number %d exiting.\n", (int)data);
    27 	return 0;
    28 }
    29 
    30 static void killed(int sig)
    31 {
    32 	alive = 0;
    33 }
    34 
    35 int main(int argc, char **argv)
    36 {
    37 	SDL_Thread *threads[NUM_THREADS];
    38 	int i, init_sem;
    39 
    40 	if(argc < 2) {
    41 		fprintf(stderr,"Usage: %s init_value\n", argv[0]);
    42 		return(1);
    43 	}
    44 
    45 	/* Load the SDL library */
    46 	if ( SDL_Init(0) < 0 ) {
    47 		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
    48 		return(1);
    49 	}
    50 	signal(SIGTERM, killed);
    51 	signal(SIGINT, killed);
    52 	
    53 	init_sem = atoi(argv[1]);
    54 	sem = SDL_CreateSemaphore(init_sem);
    55 	
    56 	printf("Running %d threads, semaphore value = %d\n", NUM_THREADS, init_sem);
    57 	/* Create all the threads */
    58 	for( i = 0; i < NUM_THREADS; ++i ) {
    59 		threads[i] = SDL_CreateThread(ThreadFunc, (void*)i);
    60 	}
    61 
    62 	/* Wait 10 seconds */
    63 	SDL_Delay(10 * 1000);
    64 
    65 	/* Wait for all threads to finish */
    66 	printf("Waiting for threads to finish\n");
    67 	alive = 0;
    68 	for( i = 0; i < NUM_THREADS; ++i ) {
    69 		SDL_WaitThread(threads[i], NULL);
    70 	}
    71 	printf("Finished waiting for threads\n");
    72 
    73 	SDL_DestroySemaphore(sem);
    74 	SDL_Quit();
    75 	return(0);
    76 }