testthread.c (2628B)
1/* 2 Copyright (C) 1997-2014 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/* Simple test of the SDL threading code */ 14 15#include <stdio.h> 16#include <stdlib.h> 17#include <signal.h> 18 19#include "SDL.h" 20#include "SDL_thread.h" 21 22static SDL_TLSID tls; 23static int alive = 0; 24 25/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */ 26static void 27quit(int rc) 28{ 29 SDL_Quit(); 30 exit(rc); 31} 32 33int SDLCALL 34ThreadFunc(void *data) 35{ 36 SDL_TLSSet(tls, "baby thread", NULL); 37 SDL_Log("Started thread %s: My thread id is %lu, thread data = %s\n", 38 (char *) data, SDL_ThreadID(), (const char *)SDL_TLSGet(tls)); 39 while (alive) { 40 SDL_Log("Thread '%s' is alive!\n", (char *) data); 41 SDL_Delay(1 * 1000); 42 } 43 SDL_Log("Thread '%s' exiting!\n", (char *) data); 44 return (0); 45} 46 47static void 48killed(int sig) 49{ 50 SDL_Log("Killed with SIGTERM, waiting 5 seconds to exit\n"); 51 SDL_Delay(5 * 1000); 52 alive = 0; 53 quit(0); 54} 55 56int 57main(int argc, char *argv[]) 58{ 59 SDL_Thread *thread; 60 61 /* Enable standard application logging */ 62 SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); 63 64 /* Load the SDL library */ 65 if (SDL_Init(0) < 0) { 66 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError()); 67 return (1); 68 } 69 70 tls = SDL_TLSCreate(); 71 SDL_assert(tls); 72 SDL_TLSSet(tls, "main thread", NULL); 73 SDL_Log("Main thread data initially: %s\n", (const char *)SDL_TLSGet(tls)); 74 75 alive = 1; 76 thread = SDL_CreateThread(ThreadFunc, "One", "#1"); 77 if (thread == NULL) { 78 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create thread: %s\n", SDL_GetError()); 79 quit(1); 80 } 81 SDL_Delay(5 * 1000); 82 SDL_Log("Waiting for thread #1\n"); 83 alive = 0; 84 SDL_WaitThread(thread, NULL); 85 86 SDL_Log("Main thread data finally: %s\n", (const char *)SDL_TLSGet(tls)); 87 88 alive = 1; 89 signal(SIGTERM, killed); 90 thread = SDL_CreateThread(ThreadFunc, "Two", "#2"); 91 if (thread == NULL) { 92 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create thread: %s\n", SDL_GetError()); 93 quit(1); 94 } 95 raise(SIGTERM); 96 97 SDL_Quit(); /* Never reached */ 98 return (0); /* Never reached */ 99}