1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
|
/*
* thread.h
*
* thread classes
*
* Copyright (c) 2004 by FORCE Computers.
*
* 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. This
* file and program are licensed under a BSD style license. See
* the Copying file included with the OpenHPI distribution for
* full licensing terms.
*
* Authors:
* Thomas Kanngieser <thomas.kanngieser@fci.com>
*/
#ifndef dThread_h
#define dThread_h
#include <pthread.h>
#include <unistd.h>
enum tTheadState
{
eTsUnknown,
eTsSuspend,
eTsRun,
eTsExit
};
// thread class
class cThread
{
protected:
pthread_t m_thread;
bool m_main; // true => main thread
tTheadState m_state;
static void *Thread( void *param );
public:
cThread();
cThread( const pthread_t &thread, bool main_thread, tTheadState state );
virtual ~cThread();
// get the current thread class
static cThread *GetThread();
// start thread
virtual bool Start();
// wait for thread termination
virtual bool Wait( void *&rv );
bool IsRunning() { return m_state == eTsRun; }
bool IsMain() { return m_main; }
protected:
virtual void *Run() = 0;
virtual void Exit( void *rv );
};
// simple locks
class cThreadLock
{
protected:
pthread_mutex_t m_lock;
public:
cThreadLock();
virtual ~cThreadLock();
virtual void Lock();
virtual void Unlock();
virtual bool TryLock();
};
class cThreadLockAuto
{
cThreadLock &m_lock;
public:
cThreadLockAuto( cThreadLock &lock )
: m_lock( lock )
{
m_lock.Lock();
}
~cThreadLockAuto()
{
m_lock.Unlock();
}
};
// read/write locks
class cThreadLockRw
{
protected:
pthread_rwlock_t m_rwlock;
public:
cThreadLockRw();
virtual ~cThreadLockRw();
virtual void ReadLock();
virtual void ReadUnlock();
virtual bool TryReadLock();
virtual void WriteLock();
virtual void WriteUnlock();
virtual bool TryWriteLock();
// true => no lock held
bool CheckLock();
};
// condition class
class cThreadCond : public cThreadLock
{
protected:
pthread_cond_t m_cond;
public:
cThreadCond();
virtual ~cThreadCond();
// call Lock before Signal
virtual void Signal();
// call Lock before Wait
virtual void Wait();
};
#endif
|