comparison test/testsem.c @ 0:74212992fb08

Initial revision
author Sam Lantinga <slouken@lokigames.com>
date Thu, 26 Apr 2001 16:45:43 +0000
parents
children be9c9c8f6d53
comparison
equal deleted inserted replaced
-1:000000000000 0:74212992fb08
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 exit(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 exit(1);
49 }
50 atexit(SDL_Quit);
51 signal(SIGTERM, killed);
52 signal(SIGINT, killed);
53
54 init_sem = atoi(argv[1]);
55 sem = SDL_CreateSemaphore(init_sem);
56
57 printf("Running %d threads, semaphore value = %d\n", NUM_THREADS, init_sem);
58 /* Create all the threads */
59 for( i = 0; i < NUM_THREADS; ++i ) {
60 threads[i] = SDL_CreateThread(ThreadFunc, (void*)i);
61 }
62
63 /* Wait 10 seconds */
64 SDL_Delay(10 * 1000);
65
66 /* Wait for all threads to finish */
67 printf("Waiting for threads to finish\n");
68 alive = 0;
69 for( i = 0; i < NUM_THREADS; ++i ) {
70 SDL_WaitThread(threads[i], NULL);
71 }
72 printf("Finished waiting for threads\n");
73
74 SDL_DestroySemaphore(sem);
75 return(0);
76 }