test/torturethread.c
author Sam Lantinga <slouken@libsdl.org>
Mon, 29 May 2006 04:04:35 +0000
branchSDL-1.3
changeset 1668 4da1ee79c9af
parent 1662 782fd950bd46
permissions -rw-r--r--
more tweaking indent options
     1 
     2 /* Simple test of the SDL threading code */
     3 
     4 #include <stdio.h>
     5 #include <stdlib.h>
     6 #include <signal.h>
     7 #include <string.h>
     8 
     9 #include "SDL.h"
    10 #include "SDL_thread.h"
    11 
    12 #define NUMTHREADS 10
    13 
    14 static char volatile time_for_threads_to_die[NUMTHREADS];
    15 
    16 /* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
    17 static void
    18 quit(int rc)
    19 {
    20     SDL_Quit();
    21     exit(rc);
    22 }
    23 
    24 int SDLCALL
    25 SubThreadFunc(void *data)
    26 {
    27     while (!*(int volatile *) data) {
    28         ;                       /*SDL_Delay(10); *//* do nothing */
    29     }
    30     return 0;
    31 }
    32 
    33 int SDLCALL
    34 ThreadFunc(void *data)
    35 {
    36     SDL_Thread *sub_threads[NUMTHREADS];
    37     int flags[NUMTHREADS];
    38     int i;
    39     int tid = (int) (uintptr_t) data;
    40 
    41     fprintf(stderr, "Creating Thread %d\n", tid);
    42 
    43     for (i = 0; i < NUMTHREADS; i++) {
    44         flags[i] = 0;
    45         sub_threads[i] = SDL_CreateThread(SubThreadFunc, &flags[i]);
    46     }
    47 
    48     printf("Thread '%d' waiting for signal\n", tid);
    49     while (time_for_threads_to_die[tid] != 1) {
    50         ;                       /* do nothing */
    51     }
    52 
    53     printf("Thread '%d' sending signals to subthreads\n", tid);
    54     for (i = 0; i < NUMTHREADS; i++) {
    55         flags[i] = 1;
    56         SDL_WaitThread(sub_threads[i], NULL);
    57     }
    58 
    59     printf("Thread '%d' exiting!\n", tid);
    60 
    61     return 0;
    62 }
    63 
    64 int
    65 main(int argc, char *argv[])
    66 {
    67     SDL_Thread *threads[NUMTHREADS];
    68     int i;
    69 
    70     /* Load the SDL library */
    71     if (SDL_Init(0) < 0) {
    72         fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
    73         return (1);
    74     }
    75 
    76     signal(SIGSEGV, SIG_DFL);
    77     for (i = 0; i < NUMTHREADS; i++) {
    78         time_for_threads_to_die[i] = 0;
    79         threads[i] = SDL_CreateThread(ThreadFunc, (void *) (uintptr_t) i);
    80 
    81         if (threads[i] == NULL) {
    82             fprintf(stderr, "Couldn't create thread: %s\n", SDL_GetError());
    83             quit(1);
    84         }
    85     }
    86 
    87     for (i = 0; i < NUMTHREADS; i++) {
    88         time_for_threads_to_die[i] = 1;
    89     }
    90 
    91     for (i = 0; i < NUMTHREADS; i++) {
    92         SDL_WaitThread(threads[i], NULL);
    93     }
    94     SDL_Quit();
    95     return (0);
    96 }