Skip to content

Latest commit

 

History

History
102 lines (90 loc) · 2.21 KB

testlock.c

File metadata and controls

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