/*
 * --- GSMP-COPYRIGHT-NOTE-BEGIN ---
 * 
 * This copyright note is auto-generated by ./scripts/Create-CopyPatch.
 * Please add additional copyright information _after_ the line containing
 * the GSMP-COPYRIGHT-NOTE-END tag. Otherwise it might get removed by
 * the ./scripts/Create-CopyPatch script. Do not edit this copyright text!
 * 
 * GSMP: utility/include/Threads.hh
 * General Sound Manipulation Program is Copyright (C) 2000 - 2009
 *   Valentin Ziegler and René Rebe
 * 
 * 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; version 2. A copy of the GNU General
 * Public License can be found in the file LICENSE.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANT-
 * ABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 * 
 * --- GSMP-COPYRIGHT-NOTE-END ---
 */

/*
 * A Pthread wrapper based on a former implementation from the sigc++
 * package by Karl Nelson.
 *
 */

#ifndef UTILITY__THREAD_HH__
#define UTILITY__THREAD_HH__

// ?? ...
#define THREAD_API

#include <pthread.h>

namespace Utility
{
  namespace Threads
  {
    struct CondAttr { pthread_condattr_t* impl; };
    struct MutexAttr { pthread_mutexattr_t* impl; };
    struct ThreadAttr { pthread_attr_t* impl; };

    typedef pthread_mutex_t MutexImpl;
    typedef pthread_cond_t CondImpl;
    typedef pthread_key_t KeyImpl;
    typedef pthread_t ThreadImpl;

    // Mutual Exclusion
    class Mutex
    {
      typedef MutexImpl Impl;
    
    public:
      
      static THREAD_API MutexAttr Default;
      
      operator Impl* ()  { return (Impl*)(&mutex); }

      Mutex (const MutexAttr attr = Default) {
	pthread_mutex_init (&mutex, attr.impl);
      };

      Mutex (int type) {
	pthread_mutexattr_t attr;
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_settype(&attr, type);

	pthread_mutex_init (&mutex, &attr);

	pthread_mutexattr_destroy(&attr); // TODO: required to hold during mutex lifetime?
      };
      
      // (needs work) 
      ~Mutex() { Destroy (); };
      
      int Lock () { return pthread_mutex_lock (&mutex); };
      int TryLock() { return pthread_mutex_trylock (&mutex); };
      int Unlock() { return pthread_mutex_unlock (&mutex); };
      
    private:
      Impl mutex;
      int Destroy() { return pthread_mutex_destroy (&mutex); };
    };

    // A lazy way to unlock at end of scope
    class MLock
    {
    public:
      MLock (Mutex& mutex) : mutex(mutex) { mutex.Lock(); };
      ~MLock () { mutex.Unlock(); };
      
    private:
      Mutex& mutex;
    };

    // Condition Variable
    class Condition
    {
    private:
      typedef CondImpl Impl;
    
    public:
      static THREAD_API CondAttr Default;
      operator Impl* ()  { return (Impl*)(&cond); };

      Condition (const CondAttr &attr = Default) {
	pthread_cond_init (&cond, attr.impl);
      };
	
      ~Condition () { Destroy (); };
      
      // restarts exactly one thread hung on condition
      int Signal ()       { return pthread_cond_signal (&cond); }

      // restarts all threads waiting on condition
      int Broadcast ()    { return pthread_cond_broadcast (&cond); }

      // unlocks a mutex while waiting on a condition, then reaquires lock.
      int Wait (Mutex &m) { return pthread_cond_wait (&cond, m); }

      // unlocks a mutex while waiting on a condition, then reaquires lock
      // with a fixed maximum duration.
      int Wait (Mutex &m, struct timespec* spec) {
	return pthread_cond_timedwait (&cond, m, spec);
      }
      
    private:
      Impl cond;
      
      int Destroy () { return pthread_cond_destroy (&cond); }
    };

    // Integer Semaphore
    class Semaphore
    {
    public:
      Semaphore (int i_value = 1)
	: value (i_value) {}
      ~Semaphore () {}
      
      void Up ();
      void Down ();
      
    private:
      int value;
      Condition sig;
      Mutex access;
    };
    
    /* This is a very basic thread skeleton.
     */
    class Thread
    {
    protected:
      typedef ThreadImpl Impl;
      static THREAD_API ThreadAttr Default;
      
    public:
      Thread (const ThreadAttr& i_attr = Default);
      virtual ~Thread ();

      /* Create () creates the new thread of execution of the given
	 instance.  Internally the thread of execution starts in the
	 private main method. arg is for passing extra data to main,
	 but never pass a local variable or address of local
	 variable. Arg must be available throughout the lifetime of
	 the program. */
      int Create (void* arg = 0);
      
      /* Detach () put the thread th in the detached state. This
	 guarantees that the memory resources consumed by th will be
	 freed immediately when th terminates. However, this prevents
	 other threads from synchronizing on the termination of this
	 thread using Join (). */
      int Detach ();
      
      /* Join () suspends the execution of the calling Thread until
	 this thread terminates, either by returning from the main ()
	 method or by being Cancel ()ed. */
      void* Join ();
      
      /* StopInDebugger () will emit a SIGTRAP (or pefroming other
	 actions valid for the given plaform) from the calling
	 thread. */
      static void StopInDebugger ();

#ifdef __linux__
      /* EnableRealtimeScheduling () enables rea-time scheduling for
	 the calling thread. */
      static bool EnableRealtimeScheduling ();
#endif

      /* USleep () suspends execution of the calling thread/process
	 for (at least) usec microseconds.  The sleep may be
	 lengthened slightly by any system activity or by the time
	 spent processing the call or by the granularity of system
	 timers. If high_precission is set to false (the default)
	 USleep will limit the minimal value where the Operating
	 System will release sleep instead of an busy loop (2ms on
	 Linux) */
      static void USleep (int usec, bool high_precission = false);
      
      /* NSleep () suspsends execution of the calling thread/process
	 in the same was as USleep - but with nanosecond precission */
      static void NSleep (int nsec, bool high_precission = false);
      
      /* A thread can relinquish the processor voluntarily without
	 blocking by calling Yield. The thread will then be moved to
	 the end of the queue for its static priority and a new
	 thread/process gets to run.

	 Note: If the current thread is the only thread/process in the
	 highest priority list at that time, this process will
	 continue to run after a call to sched_yield. */
      static void Yield ();
      
      /* SetPriotry () sets the scheduling priority of the
	 thread. Priority is a value in the range -20 to 20. The
	 default priority is 0; lower priorities cause more favorable
	 scheduling. */
      static bool SetPriority (int priority);
      
      /* Priority obtains the current priority of the calling
	 thread. */
      static int Priority ();
      
      operator Impl* () { return &thread; }
      
    protected:
      
      // the real code for the thread
      virtual void* main (void* arg) = 0;
      
      // trampolines
      void* call_main_ (void* arg);
      static void* call_main_static_ (void* arg);
      
      Impl thread;
      void* arg_;
      ThreadAttr attr;
    };
    
  } /* namespace Threads */
} /* namespace Utility */

#endif /* __UTILITY_THREAD_HH__ */
