SDL

Форк
0
/
testrwlock.c 
178 строк · 5.5 Кб
1
/*
2
  Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
3

4
  This software is provided 'as-is', without any express or implied
5
  warranty.  In no event will the authors be held liable for any damages
6
  arising from the use of this software.
7

8
  Permission is granted to anyone to use this software for any purpose,
9
  including commercial applications, and to alter it and redistribute it
10
  freely.
11
*/
12

13
/* Test the thread and rwlock locking functions
14
   Also exercises the system's signal/thread interaction
15
*/
16

17
#include <SDL3/SDL.h>
18
#include <SDL3/SDL_main.h>
19
#include <SDL3/SDL_test.h>
20

21
static SDL_RWLock *rwlock = NULL;
22
static SDL_ThreadID mainthread;
23
static SDL_AtomicInt doterminate;
24
static int nb_threads = 6;
25
static SDL_Thread **threads;
26
static int worktime = 1000;
27
static int writerworktime = 100;
28
static int timeout = 10000;
29
static SDLTest_CommonState *state;
30

31
static void DoWork(const int workticks)  /* "Work" */
32
{
33
    const SDL_ThreadID tid = SDL_GetCurrentThreadID();
34
    const SDL_bool is_reader = tid != mainthread;
35
    const char *typestr = is_reader ? "Reader" : "Writer";
36

37
    SDL_Log("%s Thread %" SDL_PRIu64 ": ready to work\n", typestr, tid);
38
    if (is_reader) {
39
        SDL_LockRWLockForReading(rwlock);
40
    } else {
41
        SDL_LockRWLockForWriting(rwlock);
42
    }
43

44
    SDL_Log("%s Thread %" SDL_PRIu64 ": start work!\n", typestr, tid);
45
    SDL_Delay(workticks);
46
    SDL_Log("%s Thread %" SDL_PRIu64 ": work done!\n", typestr, tid);
47
    SDL_UnlockRWLock(rwlock);
48

49
    /* If this sleep isn't done, then threads may starve */
50
    SDL_Delay(10);
51
}
52

53
static int SDLCALL
54
ReaderRun(void *data)
55
{
56
    SDL_Log("Reader Thread %" SDL_PRIu64 ": starting up", SDL_GetCurrentThreadID());
57
    while (!SDL_AtomicGet(&doterminate)) {
58
        DoWork(worktime);
59
    }
60
    SDL_Log("Reader Thread %" SDL_PRIu64 ": exiting!\n", SDL_GetCurrentThreadID());
61
    return 0;
62
}
63

64
int main(int argc, char *argv[])
65
{
66
    int i;
67

68
    /* Initialize test framework */
69
    state = SDLTest_CommonCreateState(argv, 0);
70
    if (!state) {
71
        return 1;
72
    }
73

74
    SDL_AtomicSet(&doterminate, 0);
75

76
    /* Enable standard application logging */
77
    SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
78
    /* Parse commandline */
79
    for (i = 1; i < argc;) {
80
        int consumed;
81

82
        consumed = SDLTest_CommonArg(state, i);
83
        if (!consumed) {
84
            if (SDL_strcmp(argv[i], "--nbthreads") == 0) {
85
                if (argv[i + 1]) {
86
                    char *endptr;
87
                    nb_threads = SDL_strtol(argv[i + 1], &endptr, 0);
88
                    if (endptr != argv[i + 1] && *endptr == '\0' && nb_threads > 0) {
89
                        consumed = 2;
90
                    }
91
                }
92
            } else if (SDL_strcmp(argv[i], "--worktime") == 0) {
93
                if (argv[i + 1]) {
94
                    char *endptr;
95
                    worktime = SDL_strtol(argv[i + 1], &endptr, 0);
96
                    if (endptr != argv[i + 1] && *endptr == '\0' && worktime > 0) {
97
                        consumed = 2;
98
                    }
99
                }
100
            } else if (SDL_strcmp(argv[i], "--writerworktime") == 0) {
101
                if (argv[i + 1]) {
102
                    char *endptr;
103
                    writerworktime = SDL_strtol(argv[i + 1], &endptr, 0);
104
                    if (endptr != argv[i + 1] && *endptr == '\0' && writerworktime > 0) {
105
                        consumed = 2;
106
                    }
107
                }
108
            } else if (SDL_strcmp(argv[i], "--timeout") == 0) {
109
                if (argv[i + 1]) {
110
                    char *endptr;
111
                    timeout = (Uint64) SDL_strtol(argv[i + 1], &endptr, 0);
112
                    if (endptr != argv[i + 1] && *endptr == '\0' && timeout > 0) {
113
                        consumed = 2;
114
                    }
115
                }
116
            }
117
        }
118
        if (consumed <= 0) {
119
            static const char *options[] = {
120
                "[--nbthreads NB]",
121
                "[--worktime ms]",
122
                "[--writerworktime ms]",
123
                "[--timeout ms]",
124
                NULL,
125
            };
126
            SDLTest_CommonLogUsage(state, argv[0], options);
127
            return 1;
128
        }
129

130
        i += consumed;
131
    }
132

133
    threads = SDL_malloc(nb_threads * sizeof(SDL_Thread*));
134

135
    /* Load the SDL library */
136
    if (SDL_Init(0) < 0) {
137
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s\n", SDL_GetError());
138
        return 1;
139
    }
140

141
    SDL_AtomicSet(&doterminate, 0);
142

143
    rwlock = SDL_CreateRWLock();
144
    if (!rwlock) {
145
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create rwlock: %s\n", SDL_GetError());
146
        SDL_Quit();
147
        SDLTest_CommonDestroyState(state);
148
        return 1;
149
    }
150

151
    mainthread = SDL_GetCurrentThreadID();
152
    SDL_Log("Writer thread: %" SDL_PRIu64 "\n", mainthread);
153
    for (i = 0; i < nb_threads; ++i) {
154
        char name[64];
155
        (void)SDL_snprintf(name, sizeof(name), "Reader%d", i);
156
        threads[i] = SDL_CreateThread(ReaderRun, name, NULL);
157
        if (threads[i] == NULL) {
158
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create reader thread! %s\n", SDL_GetError());
159
        }
160
    }
161

162
    while (!SDL_AtomicGet(&doterminate) && (SDL_GetTicks() < ((Uint64) timeout))) {
163
        DoWork(writerworktime);
164
    }
165

166
    SDL_AtomicSet(&doterminate, 1);
167
    SDL_Log("Waiting on reader threads to terminate...");
168
    for (i = 0; i < nb_threads; ++i) {
169
        SDL_WaitThread(threads[i], NULL);
170
    }
171

172
    SDL_Log("Reader threads have terminated, quitting!");
173
    SDL_DestroyRWLock(rwlock);
174
    SDL_Quit();
175
    SDLTest_CommonDestroyState(state);
176

177
    return 0;
178
}
179

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.