This repository has been archived by the owner on Feb 11, 2021. It is now read-only.
/
testlock.c
111 lines (97 loc) · 2.5 KB
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];
16
static volatile int doterminate = 0;
17
18
19
20
21
/*
* SDL_Quit() shouldn't be used with atexit() directly because
* calling conventions may differ...
*/
22
23
static void
SDL_Quit_Wrapper(void)
24
{
25
SDL_Quit();
26
27
}
28
29
void
printid(void)
30
{
31
printf("Process %u: exiting\n", SDL_ThreadID());
32
}
33
34
35
void
terminate(int sig)
36
{
37
38
signal(SIGINT, terminate);
doterminate = 1;
39
}
40
41
42
void
closemutex(int sig)
43
{
44
45
46
Uint32 id = SDL_ThreadID();
int i;
printf("Process %u: Cleaning up...\n", id == mainthread ? 0 : id);
47
doterminate = 1;
48
for (i = 0; i < 6; ++i)
49
SDL_WaitThread(threads[i], NULL);
50
51
SDL_DestroyMutex(mutex);
exit(sig);
52
}
53
54
55
int SDLCALL
Run(void *data)
56
{
57
58
if (SDL_ThreadID() == mainthread)
signal(SIGTERM, closemutex);
59
while (!doterminate) {
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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);
74
75
76
77
}
if (SDL_ThreadID() == mainthread && doterminate) {
printf("Process %u: raising SIGTERM\n", SDL_ThreadID());
raise(SIGTERM);
78
79
}
return (0);
80
81
}
82
83
int
main(int argc, char *argv[])
84
{
85
86
int i;
int maxproc = 6;
87
88
89
90
91
92
93
/* Load the SDL library */
if (SDL_Init(0) < 0) {
fprintf(stderr, "%s\n", SDL_GetError());
exit(1);
}
atexit(SDL_Quit_Wrapper);
94
95
96
97
98
if ((mutex = SDL_CreateMutex()) == NULL) {
fprintf(stderr, "Couldn't create mutex: %s\n", SDL_GetError());
exit(1);
}
99
100
101
102
103
104
105
106
107
108
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);
109
110
return (0); /* Never reached */
111
}