test/testsem.c
changeset 0 74212992fb08
child 1151 be9c9c8f6d53
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/test/testsem.c	Thu Apr 26 16:45:43 2001 +0000
     1.3 @@ -0,0 +1,76 @@
     1.4 +
     1.5 +/* Simple test of the SDL semaphore code */
     1.6 +
     1.7 +#include <stdio.h>
     1.8 +#include <stdlib.h>
     1.9 +#include <signal.h>
    1.10 +
    1.11 +#include "SDL.h"
    1.12 +#include "SDL_thread.h"
    1.13 +
    1.14 +#define NUM_THREADS 10
    1.15 +
    1.16 +static SDL_sem *sem;
    1.17 +int alive = 1;
    1.18 +
    1.19 +int ThreadFunc(void *data)
    1.20 +{
    1.21 +	while ( alive ) {
    1.22 +		SDL_SemWait(sem);
    1.23 +		fprintf(stderr, "Thread number %d has got the semaphore (value = %d)!\n", (int)data, SDL_SemValue(sem));
    1.24 +		SDL_Delay(200);
    1.25 +		SDL_SemPost(sem);
    1.26 +		fprintf(stderr, "Thread number %d has released the semaphore (value = %d)!\n", (int)data, SDL_SemValue(sem));
    1.27 +		SDL_Delay(1); /* For the scheduler */
    1.28 +	}
    1.29 +	printf("Thread number %d exiting.\n", (int)data);
    1.30 +	return 0;
    1.31 +}
    1.32 +
    1.33 +static void killed(int sig)
    1.34 +{
    1.35 +	alive = 0;
    1.36 +}
    1.37 +
    1.38 +int main(int argc, char **argv)
    1.39 +{
    1.40 +	SDL_Thread *threads[NUM_THREADS];
    1.41 +	int i, init_sem;
    1.42 +
    1.43 +	if(argc < 2) {
    1.44 +		fprintf(stderr,"Usage: %s init_value\n", argv[0]);
    1.45 +		exit(1);
    1.46 +	}
    1.47 +
    1.48 +	/* Load the SDL library */
    1.49 +	if ( SDL_Init(0) < 0 ) {
    1.50 +		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
    1.51 +		exit(1);
    1.52 +	}
    1.53 +	atexit(SDL_Quit);
    1.54 +	signal(SIGTERM, killed);
    1.55 +	signal(SIGINT, killed);
    1.56 +	
    1.57 +	init_sem = atoi(argv[1]);
    1.58 +	sem = SDL_CreateSemaphore(init_sem);
    1.59 +	
    1.60 +	printf("Running %d threads, semaphore value = %d\n", NUM_THREADS, init_sem);
    1.61 +	/* Create all the threads */
    1.62 +	for( i = 0; i < NUM_THREADS; ++i ) {
    1.63 +		threads[i] = SDL_CreateThread(ThreadFunc, (void*)i);
    1.64 +	}
    1.65 +
    1.66 +	/* Wait 10 seconds */
    1.67 +	SDL_Delay(10 * 1000);
    1.68 +
    1.69 +	/* Wait for all threads to finish */
    1.70 +	printf("Waiting for threads to finish\n");
    1.71 +	alive = 0;
    1.72 +	for( i = 0; i < NUM_THREADS; ++i ) {
    1.73 +		SDL_WaitThread(threads[i], NULL);
    1.74 +	}
    1.75 +	printf("Finished waiting for threads\n");
    1.76 +
    1.77 +	SDL_DestroySemaphore(sem);
    1.78 +	return(0);
    1.79 +}