test/testthread.c
author Sam Lantinga <slouken@libsdl.org>
Fri, 08 Apr 2011 13:03:26 -0700
changeset 5535 96594ac5fd1a
parent 5508 60b63c32f06d
child 5969 3a041d215edc
permissions -rw-r--r--
SDL 1.3 is now under the zlib license.
     1 /*
     2   Copyright (C) 1997-2011 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 
    22 static int alive = 0;
    23 
    24 /* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
    25 static void
    26 quit(int rc)
    27 {
    28     SDL_Quit();
    29     exit(rc);
    30 }
    31 
    32 int SDLCALL
    33 ThreadFunc(void *data)
    34 {
    35     printf("Started thread %s: My thread id is %lu\n",
    36            (char *) data, SDL_ThreadID());
    37     while (alive) {
    38         printf("Thread '%s' is alive!\n", (char *) data);
    39         SDL_Delay(1 * 1000);
    40     }
    41     printf("Thread '%s' exiting!\n", (char *) data);
    42     return (0);
    43 }
    44 
    45 static void
    46 killed(int sig)
    47 {
    48     printf("Killed with SIGTERM, waiting 5 seconds to exit\n");
    49     SDL_Delay(5 * 1000);
    50     alive = 0;
    51     quit(0);
    52 }
    53 
    54 int
    55 main(int argc, char *argv[])
    56 {
    57     SDL_Thread *thread;
    58 
    59     /* Load the SDL library */
    60     if (SDL_Init(0) < 0) {
    61         fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
    62         return (1);
    63     }
    64 
    65     alive = 1;
    66     thread = SDL_CreateThread(ThreadFunc, "#1");
    67     if (thread == NULL) {
    68         fprintf(stderr, "Couldn't create thread: %s\n", SDL_GetError());
    69         quit(1);
    70     }
    71     SDL_Delay(5 * 1000);
    72     printf("Waiting for thread #1\n");
    73     alive = 0;
    74     SDL_WaitThread(thread, NULL);
    75 
    76     alive = 1;
    77     signal(SIGTERM, killed);
    78     thread = SDL_CreateThread(ThreadFunc, "#2");
    79     if (thread == NULL) {
    80         fprintf(stderr, "Couldn't create thread: %s\n", SDL_GetError());
    81         quit(1);
    82     }
    83     raise(SIGTERM);
    84 
    85     SDL_Quit();                 /* Never reached */
    86     return (0);                 /* Never reached */
    87 }