'' SDL2-Example program:
'' Simple test of the SDL threading code and error handling
'' translated by TJF 2013
'/*
  'Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>

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

  'Permission is granted to anyone to use this software for any purpose,
  'including commercial applications, and to alter it and redistribute it
  'freely.
'*/

#INCLUDE ONCE "SDL2/SDL2.bi"

STATIC SHARED AS INTEGER alive = 0

'/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
SUB quit CDECL(BYVAL rc AS INTEGER)
  SDL_Quit()
  END rc
END SUB

FUNCTION ThreadFunc CDECL(BYVAL dat AS ANY PTR) AS INTEGER
  '/* Set the child thread error string */
  SDL_SetError(!"Thread %s (%u) had a problem: %s", _
               CAST(ZSTRING PTR, dat), SDL_ThreadID(), @"nevermind")
  WHILE alive
    SDL_Log(!"Thread '%s' is alive!\n", CAST(ZSTRING PTR, dat))
    SDL_Delay(1 * 1000)
  WEND
  SDL_Log(!"Child thread error string: %s\n", SDL_GetError())
  RETURN 0
END FUNCTION


'/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO)

'/* Load the SDL library */
IF SDL_Init(0) < 0 THEN
  SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, !"Couldn't initialize SDL: %s\n", SDL_GetError())
  END 1
END IF

'/* Set the error value for the main thread */
SDL_SetError("No worries")

alive = 1
VAR thread = SDL_CreateThread(@ThreadFunc, NULL, @"#1")
IF thread = NULL THEN
  SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, !"Couldn't create thread: %s\n", SDL_GetError())
  quit(1)
END IF

SDL_Delay(5 * 1000)
SDL_Log(!"Waiting for thread #1\n")
alive = 0
SDL_WaitThread(thread, NULL)

SDL_Log(!"Main thread error string: %s\n", SDL_GetError())

SDL_Quit()
