/***************************************************************************

    supportware
    Copyright (C) 2001-2008 by c.holzheuer
    c.holzheuer@sourceworx.org

    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.

***************************************************************************/


#ifndef DDTHREAD_H
#define DDTHREAD_H

#include <ddbaseobject.h>
#include <pthread.h>
#include <ddthreadmutex.h>
#include <ddthreadevent.h>
#include <ddthreadrunnable.h>

/// ddthread
/**
	ROTT! FIX!
*/

class ddthread;
class ddthreadkey;

class ddthread : public ddbasenamedobject
{

  friend class ddthreadkey;
  friend class ddthreadfactory;
  friend class ddthreadinitializer;

public:

  virtual ~ddthread();
  void cleanup();
  void execute();

  void wait();
  int  wait( unsigned secs );
  void exit();
  void join();
  void start();
	void cancel();
  
	inline ddthreadrunnable* get_runnable() const
  {
		return _runnable;
  }

  static void notify( ddthread* other );
  static ddthread* get_current_thread();

protected:

  enum ddthreadStatus
  {
  	DM1_THREAD_UNUSED = 0,
  	DM1_THREAD_INITED = 1,
  	DM1_THREAD_RUNNING = 2,
  	DM1_THREAD_DEAD = 3
  };

  enum
  {
  	DM1_LATCH_WAIT_LIST = 0,
  	DM1_MONITOR_WAIT_LIST = 0,
  	DM1_FACTORY_WAIT_LIST = 1
  };

  explicit ddthread( ddthreadrunnable* runnable, const ddstring& name="", bool isDaemon = false);
  void init();

  ddthreadStatus      status;
  pthread_t           tid;
  ddthreadevent       event;
  bool                isSignaled;
  ddthreadrunnable*   _runnable;
  bool                isDaemon;
  static ddthreadkey* key;
  static int debug;
  
private:

 ddthread( const ddthread& );
 ddthread& operator=(const ddthread& );


};


/***************************************************************************

    supportware
    Copyright (C) 2001-2008 by c.holzheuer
    c.holzheuer@sourceworx.org

    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.

***************************************************************************/


/// ddthreadfactory
/**

*/

class ddthreadfactory : ddbaseobject
{

friend class ddthreadinitializer;
friend class ddthread;

public:

  static ddthread *create_thread( ddthreadrunnable *runnable, const ddstring& name="", bool daemon = false );

protected:

	static ddthreadmutex    *_mutex;

	static inline void lock()
	{
		_mutex->lock();
	}

	static inline void unlock()
	{
		_mutex->unlock();
	}

};





#endif
