0
|
1
|
|
2 /* Test the thread and mutex locking functions
|
|
3 Also exercises the system's signal/thread interaction
|
|
4 */
|
|
5
|
|
6 #include <signal.h>
|
|
7 #include <stdio.h>
|
|
8 #include <stdlib.h>
|
|
9
|
|
10 #include "SDL.h"
|
|
11 #include "SDL_mutex.h"
|
|
12 #include "SDL_thread.h"
|
|
13
|
|
14 static SDL_mutex *mutex = NULL;
|
|
15 static Uint32 mainthread;
|
|
16 static SDL_Thread *threads[6];
|
|
17
|
|
18 void printid(void)
|
|
19 {
|
|
20 printf("Process %u: exiting\n", SDL_ThreadID());
|
|
21 }
|
|
22
|
|
23 void terminate(int sig)
|
|
24 {
|
|
25 printf("Process %u: raising SIGTERM\n", SDL_ThreadID());
|
|
26 raise(SIGTERM);
|
|
27 }
|
|
28 void closemutex(int sig)
|
|
29 {
|
|
30 Uint32 id = SDL_ThreadID();
|
|
31 int i;
|
|
32 printf("Process %u: Cleaning up...\n", id == mainthread ? 0 : id);
|
|
33 for ( i=0; i<6; ++i )
|
|
34 SDL_KillThread(threads[i]);
|
|
35 SDL_DestroyMutex(mutex);
|
|
36 exit(sig);
|
|
37 }
|
|
38 int Run(void *data)
|
|
39 {
|
|
40 if ( SDL_ThreadID() == mainthread )
|
|
41 signal(SIGTERM, closemutex);
|
|
42 while ( 1 ) {
|
|
43 printf("Process %u ready to work\n", SDL_ThreadID());
|
|
44 if ( SDL_mutexP(mutex) < 0 ) {
|
|
45 fprintf(stderr, "Couldn't lock mutex: %s", SDL_GetError());
|
|
46 exit(1);
|
|
47 }
|
|
48 printf("Process %u, working!\n", SDL_ThreadID());
|
|
49 SDL_Delay(1*1000);
|
|
50 printf("Process %u, done!\n", SDL_ThreadID());
|
|
51 if ( SDL_mutexV(mutex) < 0 ) {
|
|
52 fprintf(stderr, "Couldn't unlock mutex: %s", SDL_GetError());
|
|
53 exit(1);
|
|
54 }
|
|
55 /* If this sleep isn't done, then threads may starve */
|
|
56 SDL_Delay(10);
|
|
57 }
|
|
58 return(0);
|
|
59 }
|
|
60
|
|
61 int main(int argc, char *argv[])
|
|
62 {
|
|
63 int i;
|
|
64 int maxproc = 6;
|
|
65
|
|
66 /* Load the SDL library */
|
|
67 if ( SDL_Init(0) < 0 ) {
|
|
68 fprintf(stderr, "%s\n", SDL_GetError());
|
|
69 exit(1);
|
|
70 }
|
|
71 atexit(SDL_Quit);
|
|
72
|
|
73 if ( (mutex=SDL_CreateMutex()) == NULL ) {
|
|
74 fprintf(stderr, "Couldn't create mutex: %s\n", SDL_GetError());
|
|
75 exit(1);
|
|
76 }
|
|
77
|
|
78 mainthread = SDL_ThreadID();
|
|
79 printf("Main thread: %u\n", mainthread);
|
|
80 atexit(printid);
|
|
81 for ( i=0; i<maxproc; ++i ) {
|
|
82 if ( (threads[i]=SDL_CreateThread(Run, NULL)) == NULL )
|
|
83 fprintf(stderr, "Couldn't create thread!\n");
|
|
84 }
|
|
85 signal(SIGINT, terminate);
|
|
86 Run(NULL);
|
|
87
|
|
88 return(0); /* Never reached */
|
|
89 }
|