2 /* Test the thread and mutex locking functions
3 Also exercises the system's signal/thread interaction
10 #include "SDL_mutex.h"
11 #include "SDL_thread.h"
13 static SDL_mutex
*mutex
= NULL
;
14 static Uint32 mainthread
;
15 static SDL_Thread
*threads
[6];
16 static volatile int doterminate
= 0;
19 * SDL_Quit() shouldn't be used with atexit() directly because
20 * calling conventions may differ...
22 static void SDL_Quit_Wrapper(void)
29 printf("Process %u: exiting\n", SDL_ThreadID());
32 void terminate(int sig
)
34 signal(SIGINT
, terminate
);
37 void closemutex(int sig
)
39 Uint32 id
= SDL_ThreadID();
41 printf("Process %u: Cleaning up...\n", id
== mainthread
? 0 : id
);
43 SDL_KillThread(threads
[i
]);
44 SDL_DestroyMutex(mutex
);
47 int SDLCALL
Run(void *data
)
49 if ( SDL_ThreadID() == mainthread
)
50 signal(SIGTERM
, closemutex
);
52 printf("Process %u ready to work\n", SDL_ThreadID());
53 if ( SDL_mutexP(mutex
) < 0 ) {
54 fprintf(stderr
, "Couldn't lock mutex: %s", SDL_GetError());
57 printf("Process %u, working!\n", SDL_ThreadID());
59 printf("Process %u, done!\n", SDL_ThreadID());
60 if ( SDL_mutexV(mutex
) < 0 ) {
61 fprintf(stderr
, "Couldn't unlock mutex: %s", SDL_GetError());
64 /* If this sleep isn't done, then threads may starve */
66 if (SDL_ThreadID() == mainthread
&& doterminate
) {
67 printf("Process %u: raising SIGTERM\n", SDL_ThreadID());
74 int main(int argc
, char *argv
[])
79 /* Load the SDL library */
80 if ( SDL_Init(0) < 0 ) {
81 fprintf(stderr
, "%s\n", SDL_GetError());
84 atexit(SDL_Quit_Wrapper
);
86 if ( (mutex
=SDL_CreateMutex()) == NULL
) {
87 fprintf(stderr
, "Couldn't create mutex: %s\n", SDL_GetError());
91 mainthread
= SDL_ThreadID();
92 printf("Main thread: %u\n", mainthread
);
94 for ( i
=0; i
<maxproc
; ++i
) {
95 if ( (threads
[i
]=SDL_CreateThread(Run
, NULL
)) == NULL
)
96 fprintf(stderr
, "Couldn't create thread!\n");
98 signal(SIGINT
, terminate
);
101 return(0); /* Never reached */