/* -*- mode: c++; c-basic-offset: 4; -*-
 *
 * MICO --- a CORBA implementation
 * Copyright (C) 1997-98 Kay Roemer & Arno Puder
 * 
 * OSThread: An abstract Thread class for MICO
 * Copyright (C) 1999 Andy Kersting & Andreas Schultz
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * Send comments and/or bug reports to:
 *                mico@informatik.uni-frankfurt.de
 *
 * $Id: pththreads.h,v 1.5 1999/12/20 16:51:49 akerst Exp $
 *
 * support for GNU Pth - The GNU Portable Threads (http://www.gnu.org/software/pth)
 *
 */

#ifndef __os_thread_pthreads_h__
#define __os_thread_pthreads_h__

static void _init (MICO_ULong _tpsize, MICO_ULong _tpincr);

/*********************************** Mutex *****************************************/

class Mutex __NAME( :public _namedObject ) {
 protected:
    pth_mutex_t _mutex;
    
 public:

    friend class CondVar;

    typedef enum { Normal, Recursive } Attribute;

    Mutex( MICO_Boolean locked = FALSE, Attribute attr = Normal )
	__NAME( :_namedObject () )
	{
            name ("<UnNamed Mutex>");
	    MUTEX_DEBUG( MT_TRACE( MICODebug::instance()->printer() 
				   << "Mutex::Mutex (locked = " << (int)locked << ", " 
				   << " attr = " << attr << ")" << endl ));
	    
	    assert( pth_mutex_init(&_mutex) );
	    if (locked) lock();
	};
    ~Mutex()
	{ 
	    MUTEX_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				   << name () << ": Mutex::~Mutex ()" << endl ));
	};
    
    MICO_ULong trylock();
    
    void lock()
	{ 
	    MUTEX_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				   << name () << ": Mutex::lock ()" << endl ));
	    pth_mutex_acquire( &_mutex, FALSE, NULL );
	};

    void unlock()
	{
	    MUTEX_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				   << name () << ": Mutex::unlock ()" << endl ));
	    pth_mutex_release( &_mutex );
	};
};

/***************************** Conditional Variable  *******************************/

class CondVar __NAME( :public _namedObject ) {
private:
    pth_cond_t  _cond;
public:
    CondVar()
	{
	    __NAME( name ("<UnNamed CondVar>") );
	    COND_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				  << name () << ": ContVar::CondVar ()" << endl ));
	    
	    pth_cond_init( &_cond );
	};
    
    ~CondVar()
	{
	    COND_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				  << name () << ": ContVar::~CondVar ()" << endl ));
	};

    
    MICO_Boolean wait( Mutex &_mutex )
	{
	    COND_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				  << name () << ": CondVar::wait ()" << endl ));
	    return ( pth_cond_await( &_cond, &_mutex._mutex, NULL ) == 0 );
	};

    MICO_Boolean timedwait( Mutex &_mutex, MICO_ULong tmout );

    void broadcast()
	{ 
	    COND_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				  << name () << ": CondVar::broadcast ()" << endl ));
	    pth_cond_notify( &_cond, TRUE );
	};

    void signal()
	{ 
	    COND_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				  << name () << ": CondVar::signal ()" << endl ));
	    pth_cond_notify( &_cond, FALSE );
	};
};

/******************************* reader/writer lock *******************************/

class rwLock __NAME( :public _namedObject ) {
 private:
    pth_rwlock_t _rwlock;
    
 public:
    rwLock() __NAME( : _namedObject () )
	{
            name ("<UnNamed rwLock>");
	    RWL_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				 << "rwLock::rwLock ()" << endl ));
	    pth_rwlock_init( &_rwlock );
	};
    ~rwLock()
	{
	    RWL_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				 << name () << ": rwLock::~rwLock ()" << endl ));
	};

    void rdlock()
	{
	    RWL_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				 << name () << ": rwLock::rdlock ()" << endl ));
	    pth_rwlock_acquire( &_rwlock, PTH_RWLOCK_RD, FALSE, NULL);
	};

    void wrlock()
	{
	    RWL_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				 << name () << ": rwLock::wrlock ()" << endl ));
	    pth_rwlock_acquire( &_rwlock, PTH_RWLOCK_RW, FALSE, NULL );
	};

    void unlock()
	{
	    RWL_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				 << name () << ": rwLock::unlock ()" << endl ));
	    pth_rwlock_release( &_rwlock );
	};
};

/********************************** Semaphore **************************************/

class Semaphore __NAME( :public _namedObject ) {
 private:
    CondVar     _cond;            
    MICO_ULong  count;            // current value

 public:
    Semaphore( unsigned int val = 0)__NAME( :_namedObject () )
{
        name ("<UnNamed Semaphore>");
	SEMA_DEBUG( MT_TRACE( MICODebug::instance()->printer()
			      << "Semaphore::Semaphore (val = " << (int)val << ")" << endl ));
	count = val;
    };

    ~Semaphore() {
	SEMA_DEBUG( MT_TRACE( MICODebug::instance()->printer()
			      << name () << ": Semaphore::~Semaphore ()" << endl ));
    };

    void wait();
    void post();
};

/******************************* basic Thread class *********************************/

class Thread __NAME( :public _namedObject ) {
 public:
    // for POSIX-Threads, a ThreadID is simply a pthread_t:
    typedef pth_t      ThreadID;
    typedef pth_key_t  ThreadKey;
    typedef MICO_ULong ThreadNo;

    typedef enum { Detached, NotDetached } DetachFlag;
    typedef enum { NoError, InvalidPriority, MutexAlreadyLocked,
		   NotStarted, UnknownError } ErrorType;

    // start method
    static void *ThreadWrapper (void *arg);
    
    static int get_priority_max() { 
	//    return sched_get_priority_max( sched_getscheduler(0) ); 
	return 0;
    };
    static int get_priority_min() {
	//    return sched_get_priority_min( sched_getscheduler(0) );
	return 0;
    };

     // key handling
    static void createKey( ThreadKey &key ) {
	assert( pth_key_create( &key, NULL ) == 0 );
    };
    static void deleteKey( ThreadKey key ) {
	assert( pth_key_delete( key ) == 0 );
    };
    static void *getSpecific( ThreadKey key ) {
	return pthr_getdata( key );
    };
    static void setSpecific( ThreadKey key, void *value ) {
	assert( pth_setdata( key, value ) == 0 );
    };
   
 protected:
    void *_arg;                   // parameters passed in via start()
    
    ThreadID _id;       // records the id from pthread_create()
    ThreadNo _no;
    DetachFlag _detached;
    
#ifdef _THR_CREATE_AND_BLOCK
    Mutex _ready;
#endif
    
 public:
    Thread (DetachFlag detached = NotDetached);
    
    void _thr_startup(void *arg) {
#ifdef _THR_CREATE_AND_BLOCK
	_ready.lock();
#endif
	_run( arg );
    };

    virtual void _run (void *arg) = 0;  // the _run() method sets up
    // anything else this object needs
    // including other threads.           
    
    // Start the thread ala JAVA:
    virtual ErrorType start (void *arg = NULL);
    
    // get this thread's ID:
    ThreadID id () const        { return _id; };
    static ThreadID self ()     { return pth_self(); };

    ThreadNo no () const        { return _no; };
    void no( const ThreadNo n ) { _no = n; };

    // see if thread `thread' is the same as this thread:
    virtual MICO_Boolean operator == (const Thread &thread) const;
    
    // create a new thread with _run a its start methode
    // maybe we should throw a exception instead of returning an error code
    ErrorType create_thread () {
	THREAD_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				<< "Thread::create_thread ()" << endl ));
#ifdef _THR_CREATE_AND_BLOCK
	_ready.lock();
#endif
	
	if (!(_id = pth_spawn( PTH_ATTR_DEFAULT, &ThreadWrapper, this)))
	    return UnknownError;
	if (_detached == Detached)
	    pth_attr_set(PTH_ATTR_DEFAULT, PTH_ATTR_JOINABLE, FALSE);
	return NoError;
    };
    
     // yield execution
    void yield() {
#ifdef HAVE_SCHED_H
	pth_yield();
#endif
    };

   // tell this thread to die:
    void terminate (void *exitval) {
	THREAD_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				<< name () << ": Thread::terminate (void *exitval)" << endl ));
	pth_cancel (_id);
    };
    
    // set the priority of this thread to `new_priority'.
    // let's avoid using this if at all possible, some pthreads impls don't
    // support it fully or at all:
    virtual void priority (MICO_Long new_priority);
    
    // wait for this thread to finish:
    void wait () {
	THREAD_DEBUG( MT_TRACE( MICODebug::instance()->printer()
				<< name () << ": Thread::wait()" << endl ));
	pth_join (id(), NULL);
    };
    
    virtual ~Thread ();
};

#endif // __os_thread_pthreads_h__
