SDL
1/*
2Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
3
4This software is provided 'as-is', without any express or implied
5warranty. In no event will the authors be held liable for any damages
6arising from the use of this software.
7
8Permission is granted to anyone to use this software for any purpose,
9including commercial applications, and to alter it and redistribute it
10freely.
11*/
12
13/* Simple test of the SDL threading code and error handling */
14
15#include <stdlib.h>16
17#include <SDL3/SDL.h>18#include <SDL3/SDL_main.h>19#include <SDL3/SDL_test.h>20
21static int alive = 0;22
23/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
24static void25quit(int rc)26{
27SDL_Quit();28/* Let 'main()' return normally */29if (rc != 0) {30exit(rc);31}32}
33
34static int SDLCALL35ThreadFunc(void *data)36{
37/* Set the child thread error string */38SDL_SetError("Thread %s (%" SDL_PRIu64 ") had a problem: %s",39(char *)data, SDL_GetCurrentThreadID(), "nevermind");40while (alive) {41SDL_Log("Thread '%s' is alive!\n", (char *)data);42SDL_Delay(1 * 1000);43}44SDL_Log("Child thread error string: %s\n", SDL_GetError());45return 0;46}
47
48int main(int argc, char *argv[])49{
50SDL_Thread *thread;51SDLTest_CommonState *state;52int i;53SDL_bool enable_threads = SDL_TRUE;54
55/* Initialize test framework */56state = SDLTest_CommonCreateState(argv, 0);57if (!state) {58return 1;59}60
61/* Enable standard application logging */62SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);63
64/* Parse commandline */65for (i = 1; i < argc;) {66int consumed;67
68consumed = SDLTest_CommonArg(state, i);69if (consumed == 0) {70consumed = -1;71if (SDL_strcasecmp(argv[i], "--no-threads") == 0) {72enable_threads = SDL_FALSE;73consumed = 1;74}75}76if (consumed < 0) {77static const char *options[] = {78"[--no-threads]",79NULL80};81SDLTest_CommonLogUsage(state, argv[0], options);82return 1;83}84i += consumed;85}86
87/* Load the SDL library */88if (SDL_Init(0) < 0) {89SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());90return 1;91}92
93/* Set the error value for the main thread */94SDL_SetError("No worries");95
96if (SDL_getenv("SDL_TESTS_QUICK") != NULL) {97SDL_Log("Not running slower tests");98SDL_Quit();99return 0;100}101
102if (enable_threads) {103alive = 1;104thread = SDL_CreateThread(ThreadFunc, NULL, "#1");105if (!thread) {106SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create thread: %s\n", SDL_GetError());107quit(1);108}109SDL_Delay(5 * 1000);110SDL_Log("Waiting for thread #1\n");111alive = 0;112SDL_WaitThread(thread, NULL);113}114
115SDL_Log("Main thread error string: %s\n", SDL_GetError());116
117SDL_Quit();118SDLTest_CommonDestroyState(state);119return 0;120}
121