/*      compthreads.cpp
//
//      Copyright 2005-2011 Lucas Tsatiris <systester.project@gmail.com>
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.
//
*/

/*
   Thread compatibility functions.
   Wrappers over posix and windows threads.
*/

#if !defined(COMPTHREADS)
#define COMPTHREADS 1

#include "compthreads.h"

static int pth_initflag = 0;
int pth_stacksize = 256*1024;

st_threadret_t
st_thread_create (st_thread_t * th,
		  st_threadfunc_t (*start_routine) (st_threadfuncarg_t),
		  st_threadfuncarg_t arg)
{
#if defined (_MSC_VER)|| defined (__MINGW32__) /* windows threads */
  LPTHREAD_START_ROUTINE startaddr;
  startaddr = (LPTHREAD_START_ROUTINE) start_routine;
  return CreateThread (NULL,	// default security attributes
		       0,	// use default stack size
		       startaddr,	// thread function
		       arg,	// argument to thread function
		       0,	// use default creation flags
		       th);	// returns the thread identifier
		       
#elif defined (_SCO_DS) /* GNU pth for SCO Openserver */
  pth_attr_t attr;
  
  if (pth_initflag == 0)
  {
    pth_init ();
    pth_initflag = 1;
  }  
  
  attr = pth_attr_new();
  pth_attr_set(attr, PTH_ATTR_NAME, "systester");
  pth_attr_set(attr, PTH_ATTR_STACK_SIZE, pth_stacksize);
  pth_attr_set(attr, PTH_ATTR_JOINABLE, TRUE);
  *th = pth_spawn(attr, start_routine, arg);
  return 0;
  
#else /* posix threads */
  return pthread_create (th, NULL, start_routine, arg);
  
#endif /*__WIN32 */
}

void
st_thread_join (int nthreads, st_thread_t * threads,
		st_threadret_t * rthreads)
{
  int i;
#if defined (_MSC_VER) || defined (__MINGW32__) /* windows threads */
  const HANDLE *th;
  th = (const HANDLE *) rthreads;

  for (i = 0; i < nthreads; i++)
    WaitForSingleObject (th[i], INFINITE);

  for (i = 0; i < nthreads; i++)
    CloseHandle (th[i]);

#elif defined (_SCO_DS) /* GNU pth for SCO Openserver */    
  for (i = 0; i < nthreads; i++)
    pth_join (threads[i], NULL);
  
#else /* posix threads */
  for (i = 0; i < nthreads; i++)
    pthread_join (threads[i], NULL);

#endif /* _MSC_VER */
}

#endif
