Started over.

This commit is contained in:
crs
2001-10-06 14:13:28 +00:00
parent 27ead1f713
commit ff81f708e2
132 changed files with 7634 additions and 3960 deletions

296
mt/CCondVar.cpp Normal file
View File

@@ -0,0 +1,296 @@
#include "CCondVar.h"
#include "CStopwatch.h"
#include <assert.h>
//
// CCondVarBase
//
CCondVarBase::CCondVarBase(CMutex* mutex) :
m_mutex(mutex)
#if defined(CONFIG_PLATFORM_WIN32)
, m_waitCountMutex()
#endif
{
assert(m_mutex != NULL);
init();
}
CCondVarBase::~CCondVarBase()
{
fini();
}
void CCondVarBase::lock() const throw()
{
m_mutex->lock();
}
void CCondVarBase::unlock() const throw()
{
m_mutex->unlock();
}
bool CCondVarBase::wait(double timeout) const
{
CStopwatch timer(true);
return wait(timer, timeout);
}
CMutex* CCondVarBase::getMutex() const throw()
{
return m_mutex;
}
#if defined(CONFIG_PTHREADS)
#include "CThread.h"
#include <pthread.h>
#include <sys/time.h>
#include <errno.h>
void CCondVarBase::init()
{
pthread_cond_t* cond = new pthread_cond_t;
int status = pthread_cond_init(cond, NULL);
assert(status == 0);
m_cond = reinterpret_cast<pthread_cond_t*>(cond);
}
void CCondVarBase::fini()
{
pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(m_cond);
int status = pthread_cond_destroy(cond);
assert(status == 0);
delete cond;
}
void CCondVarBase::signal() throw()
{
pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(m_cond);
int status = pthread_cond_signal(cond);
assert(status == 0);
}
void CCondVarBase::broadcast() throw()
{
pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(m_cond);
int status = pthread_cond_broadcast(cond);
assert(status == 0);
}
bool CCondVarBase::wait(
CStopwatch& timer, double timeout) const
{
// check timeout against timer
if (timeout >= 0.0) {
timeout -= timer.getTime();
if (timeout < 0.0)
return false;
}
// get condition variable and mutex
pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(m_cond);
pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(m_mutex->m_mutex);
// get final time
struct timeval now;
gettimeofday(&now, NULL);
struct timespec finalTime;
finalTime.tv_sec = now.tv_sec;
finalTime.tv_nsec = now.tv_usec * 1000;
if (timeout >= 0.0) {
const long timeout_sec = (long)timeout;
const long timeout_nsec = (long)(1000000000.0 * (timeout - timeout_sec));
finalTime.tv_sec += timeout_sec;
finalTime.tv_nsec += timeout_nsec;
if (finalTime.tv_nsec >= 1000000000) {
finalTime.tv_nsec -= 1000000000;
finalTime.tv_sec += 1;
}
}
// repeat until we reach the final time
int status;
for (;;) {
// compute the next timeout
gettimeofday(&now, NULL);
struct timespec endTime;
endTime.tv_sec = now.tv_sec;
endTime.tv_nsec = now.tv_usec * 1000 + 50000000;
if (endTime.tv_nsec >= 1000000000) {
endTime.tv_nsec -= 1000000000;
endTime.tv_sec += 1;
}
// see if we should cancel this thread
CThread::testCancel();
// done if past final timeout
if (timeout >= 0.0) {
if (endTime.tv_sec > finalTime.tv_sec ||
(endTime.tv_sec == finalTime.tv_sec &&
endTime.tv_nsec >= finalTime.tv_nsec)) {
status = ETIMEDOUT;
break;
}
}
// wait
status = pthread_cond_timedwait(cond, mutex, &endTime);
// check for cancel again
CThread::testCancel();
// check wait status
if (status != ETIMEDOUT)
break;
}
switch (status) {
case 0:
// success
return true;
case ETIMEDOUT:
return false;
default:
assert(0 && "condition variable wait error");
return false;
}
}
#endif // CONFIG_PTHREADS
#if defined(CONFIG_PLATFORM_WIN32)
#include "CLock.h"
#include "CThreadRep.h"
#include <windows.h>
//
// note -- implementation taken from
// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
// titled "Strategies for Implementing POSIX Condition Variables
// on Win32." it also provides an implementation that doesn't
// suffer from the incorrectness problem described in our
// corresponding header but it is slower, still unfair, and
// can cause busy waiting.
//
void CCondVarBase::init()
{
// prepare events
HANDLE* events = new HANDLE[2];
events[kSignal] = CreateEvent(NULL, FALSE, FALSE, NULL);
events[kBroadcast] = CreateEvent(NULL, TRUE, FALSE, NULL);
// prepare members
m_cond = reinterpret_cast<void*>(events);
m_waitCount = 0;
}
void CCondVarBase::fini()
{
HANDLE* events = reinterpret_cast<HANDLE*>(m_cond);
CloseHandle(events[kSignal]);
CloseHandle(events[kBroadcast]);
delete[] events;
}
void CCondVarBase::signal() throw()
{
// is anybody waiting?
bool hasWaiter;
{
CLock lock(&m_waitCountMutex);
hasWaiter = (m_waitCount > 0);
}
// wake one thread if anybody is waiting
if (hasWaiter)
SetEvent(reinterpret_cast<HANDLE*>(m_cond)[kSignal]);
}
void CCondVarBase::broadcast() throw()
{
// is anybody waiting?
bool hasWaiter;
{
CLock lock(&m_waitCountMutex);
hasWaiter = (m_waitCount > 0);
}
// wake all threads if anybody is waiting
if (hasWaiter)
SetEvent(reinterpret_cast<HANDLE*>(m_cond)[kBroadcast]);
}
bool CCondVarBase::wait(
CStopwatch& timer, double timeout) const
{
// check timeout against timer
if (timeout >= 0.0) {
timeout -= timer.getTime();
if (timeout < 0.0)
return false;
}
// prepare to wait
CRefCountedPtr<CThreadRep> currentRep(CThreadRep::getCurrentThreadRep());
const DWORD winTimeout = (timeout < 0.0) ? INFINITE :
static_cast<DWORD>(1000.0 * timeout);
HANDLE* events = reinterpret_cast<HANDLE*>(m_cond);
HANDLE handles[3];
handles[0] = events[kSignal];
handles[1] = events[kBroadcast];
handles[2] = currentRep->getCancelEvent();
const DWORD n = currentRep->isCancellable() ? 3 : 2;
// update waiter count
{
CLock lock(&m_waitCountMutex);
++m_waitCount;
}
// release mutex. this should be atomic with the wait so that it's
// impossible for another thread to signal us between the unlock and
// the wait, which would lead to a lost signal on broadcasts.
// however, we're using a manual reset event for broadcasts which
// stays set until we reset it, so we don't lose the broadcast.
m_mutex->unlock();
// wait for a signal or broadcast
DWORD result = ::WaitForMultipleObjects(n, handles, FALSE, winTimeout);
// cancel takes priority
if (n == 3 && result != WAIT_OBJECT_0 + 2 &&
::WaitForSingleObject(handles[2], 0) == WAIT_OBJECT_0)
result = WAIT_OBJECT_0 + 2;
// update the waiter count and check if we're the last waiter
bool last;
{
CLock lock(&m_waitCountMutex);
--m_waitCount;
last = (result == WAIT_OBJECT_0 + 1 && m_waitCount == 0);
}
// reset the broadcast event if we're the last waiter
if (last)
ResetEvent(events[kBroadcast]);
// reacquire the mutex
m_mutex->lock();
// cancel thread if necessary
if (result == WAIT_OBJECT_0 + 2)
currentRep->testCancel();
// return success or failure
return (result == WAIT_OBJECT_0 + 0 ||
result == WAIT_OBJECT_0 + 1);
}
#endif // CONFIG_PLATFORM_WIN32

144
mt/CCondVar.h Normal file
View File

@@ -0,0 +1,144 @@
#ifndef CCONDVAR_H
#define CCONDVAR_H
#include "CMutex.h"
#include "BasicTypes.h"
class CStopwatch;
class CCondVarBase {
public:
// mutex must be supplied. all condition variables have an
// associated mutex. the copy c'tor uses the same mutex as the
// argument and is otherwise like the default c'tor.
CCondVarBase(CMutex* mutex);
~CCondVarBase();
// manipulators
// lock/unlock the mutex. see CMutex.
void lock() const throw();
void unlock() const throw();
// signal the condition. Signal() wakes one waiting thread.
// Broadcast() wakes all waiting threads.
void signal() throw();
void broadcast() throw();
// accessors
// wait on the condition. if timeout < 0 then wait until signalled,
// otherwise up to timeout seconds or until signalled, whichever
// comes first. since clients normally wait on condition variables
// in a loop, clients can provide a CStopwatch that acts as the
// timeout clock. using it, clients don't have to recalculate the
// timeout on each iteration. passing a stopwatch with a negative
// timeout is pointless but permitted.
//
// returns true if the object was signalled during the wait, false
// otherwise.
//
// (cancellation point)
bool wait(double timeout = -1.0) const;
bool wait(CStopwatch&, double timeout) const;
// get the mutex passed to the c'tor
CMutex* getMutex() const throw();
private:
void init();
void fini();
// not implemented
CCondVarBase(const CCondVarBase&);
CCondVarBase& operator=(const CCondVarBase&);
private:
CMutex* m_mutex;
void* m_cond;
#if defined(CONFIG_PLATFORM_WIN32)
enum { kSignal, kBroadcast };
mutable UInt32 m_waitCount;
CMutex m_waitCountMutex;
#endif
};
template <class T>
class CCondVar : public CCondVarBase {
public:
CCondVar(CMutex* mutex, const T&);
CCondVar(const CCondVar&);
~CCondVar();
// manipulators
// assigns the value of the variable
CCondVar& operator=(const CCondVar&);
// assign the value
CCondVar& operator=(const T&);
// accessors
// get the const value. this object should be locked before
// calling this method.
operator const T&() const throw();
private:
T m_data;
};
template <class T>
inline
CCondVar<T>::CCondVar(CMutex* mutex, const T& data) :
CCondVarBase(mutex), m_data(data)
{
// do nothing
}
template <class T>
inline
CCondVar<T>::CCondVar(const CCondVar& cv) :
CCondVarBase(cv.getMutex()),
m_data(cv.m_data)
{
// do nothing
}
template <class T>
inline
CCondVar<T>::~CCondVar()
{
// do nothing
}
template <class T>
inline
CCondVar<T>& CCondVar<T>::operator=(const CCondVar<T>& cv)
{
m_data = cv.m_data;
return *this;
}
template <class T>
inline
CCondVar<T>& CCondVar<T>::operator=(const T& data)
{
m_data = data;
return *this;
}
template <class T>
inline
CCondVar<T>::operator const T&() const throw()
{
return m_data;
}
// force instantiation of these common types
template class CCondVar<bool>;
template class CCondVar<SInt32>;
#endif

22
mt/CLock.cpp Normal file
View File

@@ -0,0 +1,22 @@
#include "CLock.h"
#include "CMutex.h"
#include "CCondVar.h"
//
// CLock
//
CLock::CLock(const CMutex* mutex) throw() : m_mutex(mutex)
{
m_mutex->lock();
}
CLock::CLock(const CCondVarBase* cv) throw() : m_mutex(cv->getMutex())
{
m_mutex->lock();
}
CLock::~CLock() throw()
{
m_mutex->unlock();
}

24
mt/CLock.h Normal file
View File

@@ -0,0 +1,24 @@
#ifndef CLOCK_H
#define CLOCK_H
#include "common.h"
class CMutex;
class CCondVarBase;
class CLock {
public:
CLock(const CMutex* mutex) throw();
CLock(const CCondVarBase* cv) throw();
~CLock() throw();
private:
// not implemented
CLock(const CLock&);
CLock& operator=(const CLock&);
private:
const CMutex* m_mutex;
};
#endif

123
mt/CMutex.cpp Normal file
View File

@@ -0,0 +1,123 @@
#include "CMutex.h"
#include <assert.h>
//
// CMutex
//
CMutex::CMutex()
{
init();
}
CMutex::CMutex(const CMutex&)
{
init();
}
CMutex::~CMutex()
{
fini();
}
CMutex& CMutex::operator=(const CMutex&)
{
return *this;
}
#if defined(CONFIG_PTHREADS)
#include <pthread.h>
#include <errno.h>
void CMutex::init()
{
pthread_mutex_t* mutex = new pthread_mutex_t;
int status = pthread_mutex_init(mutex, NULL);
assert(status == 0);
// status = pthread_mutexattr_settype(mutex, PTHREAD_MUTEX_RECURSIVE);
// assert(status == 0);
m_mutex = reinterpret_cast<void*>(mutex);
}
void CMutex::fini()
{
pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(m_mutex);
int status = pthread_mutex_destroy(mutex);
assert(status == 0);
delete mutex;
}
void CMutex::lock() const throw()
{
pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(m_mutex);
int status = pthread_mutex_lock(mutex);
switch (status) {
case 0:
// success
return;
case EDEADLK:
assert(0 && "lock already owned");
break;
case EAGAIN:
assert(0 && "too many recursive locks");
break;
default:
assert(0 && "unexpected error");
}
}
void CMutex::unlock() const throw()
{
pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>(m_mutex);
int status = pthread_mutex_unlock(mutex);
switch (status) {
case 0:
// success
return;
case EPERM:
assert(0 && "thread doesn't own a lock");
break;
default:
assert(0 && "unexpected error");
}
}
#endif // CONFIG_PTHREADS
#if defined(CONFIG_PLATFORM_WIN32)
#include <windows.h>
void CMutex::init()
{
CRITICAL_SECTION* mutex = new CRITICAL_SECTION;
::InitializeCriticalSection(mutex);
m_mutex = reinterpret_cast<void*>(mutex);
}
void CMutex::fini()
{
CRITICAL_SECTION* mutex = reinterpret_cast<CRITICAL_SECTION*>(m_mutex);
::DeleteCriticalSection(mutex);
delete mutex;
}
void CMutex::lock() const throw()
{
::EnterCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(m_mutex));
}
void CMutex::unlock() const throw()
{
::LeaveCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(m_mutex));
}
#endif // CONFIG_PLATFORM_WIN32

35
mt/CMutex.h Normal file
View File

@@ -0,0 +1,35 @@
#ifndef CMUTEX_H
#define CMUTEX_H
#include "common.h"
// recursive mutex class
class CMutex {
public:
// copy c'tor is equivalent to default c'tor. it's here to
// allow copying of objects that have mutexes.
CMutex();
CMutex(const CMutex&);
~CMutex();
// manipulators
// this has no effect. it's only here to allow assignment of
// objects that have mutexes.
CMutex& operator=(const CMutex&);
// accessors
void lock() const throw();
void unlock() const throw();
private:
void init();
void fini();
private:
friend class CCondVarBase;
void* m_mutex;
};
#endif

131
mt/CThread.cpp Normal file
View File

@@ -0,0 +1,131 @@
#include "CThread.h"
#include "CThreadRep.h"
#include "XThread.h"
#include "CLock.h"
#include "CStopwatch.h"
//
// CThreadPtr
//
class CThreadPtr {
public:
CThreadPtr(CThreadRep* rep) : m_rep(rep) { }
~CThreadPtr() { m_rep->unref(); }
CThreadRep* operator->() const { return m_rep; }
private:
// not implemented
CThreadPtr(const CThreadPtr&);
CThreadPtr& operator=(const CThreadPtr&);
private:
CThreadRep* m_rep;
};
//
// CThread
//
CThread::CThread(IJob* job, void* userData)
{
m_rep = new CThreadRep(job, userData);
}
CThread::CThread(const CThread& thread) : m_rep(thread.m_rep)
{
m_rep->ref();
}
CThread::CThread(CThreadRep* rep) : m_rep(rep)
{
// do nothing. rep should have already been Ref()'d.
}
CThread::~CThread()
{
m_rep->unref();
}
CThread& CThread::operator=(const CThread& thread)
{
if (thread.m_rep != m_rep) {
m_rep->unref();
m_rep = thread.m_rep;
m_rep->ref();
}
return *this;
}
void CThread::sleep(double timeout)
{
CThreadPtr currentRep(CThreadRep::getCurrentThreadRep());
if (timeout >= 0.0) {
currentRep->testCancel();
currentRep->sleep(timeout);
}
currentRep->testCancel();
}
void CThread::exit(void* result)
{
throw XThreadExit(result);
}
bool CThread::enableCancel(bool enable)
{
CThreadPtr currentRep(CThreadRep::getCurrentThreadRep());
return currentRep->enableCancel(enable);
}
void CThread::cancel()
{
m_rep->cancel();
}
void CThread::setPriority(int n)
{
m_rep->setPriority(n);
}
CThread CThread::getCurrentThread()
{
return CThread(CThreadRep::getCurrentThreadRep());
}
bool CThread::wait(double timeout) const
{
CThreadPtr currentRep(CThreadRep::getCurrentThreadRep());
return currentRep->wait(m_rep, timeout);
}
void CThread::testCancel()
{
CThreadPtr currentRep(CThreadRep::getCurrentThreadRep());
currentRep->testCancel();
}
void* CThread::getResult() const
{
if (wait())
return m_rep->getResult();
else
return NULL;
}
void* CThread::getUserData()
{
CThreadPtr currentRep(CThreadRep::getCurrentThreadRep());
return currentRep->getUserData();
}
bool CThread::operator==(const CThread& thread) const
{
return (m_rep == thread.m_rep);
}
bool CThread::operator!=(const CThread& thread) const
{
return (m_rep != thread.m_rep);
}

130
mt/CThread.h Normal file
View File

@@ -0,0 +1,130 @@
#ifndef CTHREAD_H
#define CTHREAD_H
#include "common.h"
class IJob;
class CThreadRep;
// note -- do not derive from this class
class CThread {
public:
// create and start a new thread executing the job.
// the user data can be retrieved with getUserData().
CThread(IJob* adopted, void* userData = 0);
// make a new thread object that refers to an existing thread.
// this does *not* start a new thread.
CThread(const CThread&);
// release thread. this does not terminate the thread. a thread
// will keep running until the job completes or calls exit().
~CThread();
// manipulators
// assign thread. this has no effect on the threads. it simply
// makes this thread object refer to another thread. it does *not*
// start a new thread.
CThread& operator=(const CThread&);
// the calling thread sleeps for the given number of seconds. if
// timeout <= 0.0 then the call returns immediately. if timeout
// == 0.0 then the calling thread yields the CPU.
// (cancellation point)
static void sleep(double timeout);
// terminate the calling thread. this function does not return but
// the stack is unwound and automatic objects are destroyed, as if
// exit() threw an exception (which is, in fact, what it does). the
// argument is saved as the result returned by getResult(). if you
// have a catch(...) block then you should add the following before
// it to avoid catching the exit: catch(CThreadExit&) { throw; }
static void exit(void*);
// enable/disable cancellation. default is enabled. this is not
// a cancellation point so if you enabled cancellation and want to
// allow immediate cancellation you need to call testCancel().
// return value is the previous state.
static bool enableCancel(bool);
// cancel the thread. cancel() never waits for the thread to
// terminate; it just posts the cancel and returns. a thread will
// terminate when it enters a cancellation point with cancellation
// enabled. if cancellation is disabled then the cancel is
// remembered but not acted on until the first call to a
// cancellation point after cancellation is enabled.
//
// a cancellation point is a function that can act on cancellation.
// a cancellation point does not return if there's a cancel pending.
// instead, it unwinds the stack and destroys automatic objects, as
// if cancel() threw an exception (which is, in fact, what it does).
// threads must take care to clean up and release any resources they
// may have, especially mutexes. they can catch (XThreadCancel) to
// do that then rethrow the exception or they can let it happen
// automatically by doing clean up in the d'tors of automatic
// objects. clients are strongly encouraged to do the latter.
// during cancellation, further cancel() calls are ignored (i.e.
// a thread cannot be interrupted by a cancel during cancellation).
//
// clients that catch (XThreadCancel) must always rethrow the
// exception. clients that catch(...) must either rethrow the
// exception or include a catch (XThreadCancel) handler that
// rethrows.
void cancel();
// change the priority of the thread. normal priority is 0, 1 is
// the next lower, etc. -1 is the next higher, etc. but boosting
// the priority may not be available.
void setPriority(int n);
// accessors
// return a thread object representing the calling thread
static CThread getCurrentThread();
// get the user data passed to the constructor for the current
// thread.
static void* getUserData();
// testCancel() does nothing but is a cancellation point. call
// this to make a function itself a cancellation point.
// (cancellation point)
static void testCancel();
// waits for the thread to terminate (by exit() or cancel() or
// by returning from the thread job). returns immediately if
// the thread has already terminated. returns immediately with
// false if called by a thread on itself. returns false on
// timeout (or error) and true on success.
// (cancellation point)
bool wait(double timeout = -1.0) const;
// get the exit result. does an implicit wait(). returns NULL
// immediately if called by a thread on itself. returns NULL for
// threads that were cancelled.
// (cancellation point)
void* getResult() const;
// compare threads for (in)equality
bool operator==(const CThread&) const;
bool operator!=(const CThread&) const;
private:
CThread(CThreadRep*);
private:
CThreadRep* m_rep;
};
// disables cancellation in the c'tor and enables it in the d'tor.
class CThreadMaskCancel {
public:
CThreadMaskCancel() : m_old(CThread::enableCancel(false)) { }
~CThreadMaskCancel() { CThread::enableCancel(m_old); }
private:
bool m_old;
};
#endif

518
mt/CThreadRep.cpp Normal file
View File

@@ -0,0 +1,518 @@
#include "CThreadRep.h"
#include "CThread.h"
#include "XThread.h"
#include "CLock.h"
#include "IJob.h"
#include <assert.h>
#if defined(CONFIG_PTHREADS)
#include <signal.h>
#endif
// FIXME -- temporary exception type
class XThreadUnavailable { };
//
// CThreadRep
//
CMutex CThreadRep::s_mutex;
CThreadRep* CThreadRep::s_head = NULL;
CThreadRep::CThreadRep() : m_prev(NULL),
m_next(NULL),
m_refCount(1),
m_job(NULL),
m_userData(NULL)
{
// note -- s_mutex must be locked on entry
// initialize stuff
init();
#if defined(CONFIG_PTHREADS)
// get main thread id
m_thread = pthread_self();
// install SIGALRM handler
struct sigaction act;
act.sa_handler = &threadCancel;
# if defined(SA_INTERRUPT)
act.sa_flags = SA_INTERRUPT;
# else
act.sa_flags = 0;
# endif
sigemptyset(&act.sa_mask);
sigaction(SIGALRM, &act, NULL);
#elif defined(CONFIG_PLATFORM_WIN32)
// get main thread id
m_thread = NULL;
m_id = GetCurrentThreadId();
#endif
// insert ourself into linked list
if (s_head != NULL) {
s_head->m_prev = this;
m_next = s_head;
}
s_head = this;
}
CThreadRep::CThreadRep(IJob* job, void* userData) :
m_prev(NULL),
m_next(NULL),
m_refCount(2), // 1 for us, 1 for thread
m_job(job),
m_userData(userData)
{
assert(m_job != NULL);
// create a thread rep for the main thread if the current thread
// is unknown. note that this might cause multiple "main" threads
// if threads are created external to this library.
getCurrentThreadRep()->unref();
// initialize
init();
// hold mutex while we create the thread
CLock lock(&s_mutex);
// start the thread. throw if it doesn't start.
#if defined(CONFIG_PTHREADS)
int status = pthread_create(&m_thread, NULL, threadFunc, (void*)this);
if (status != 0)
throw XThreadUnavailable();
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGALRM);
pthread_sigmask(SIG_UNBLOCK, &sigset, NULL);
#elif defined(CONFIG_PLATFORM_WIN32)
unsigned int id;
m_thread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0,
threadFunc, (void*)this, 0, &id));
m_id = static_cast<DWORD>(id);
if (m_thread == 0)
throw XThreadUnavailable();
#endif
// insert ourself into linked list
if (s_head != NULL) {
s_head->m_prev = this;
m_next = s_head;
}
s_head = this;
// returning releases the locks, allowing the child thread to run
}
CThreadRep::~CThreadRep()
{
// note -- s_mutex must be locked on entry
// remove ourself from linked list
if (m_prev != NULL) {
m_prev->m_next = m_next;
}
if (m_next != NULL) {
m_next->m_prev = m_prev;
}
if (s_head == this) {
s_head = m_next;
}
// clean up
fini();
}
void CThreadRep::ref()
{
CLock lock(&s_mutex);
++m_refCount;
}
void CThreadRep::unref()
{
CLock lock(&s_mutex);
if (--m_refCount == 0) {
delete this;
}
}
bool CThreadRep::enableCancel(bool enable)
{
CLock lock(&s_mutex);
const bool old = m_cancellable;
m_cancellable = enable;
return old;
}
bool CThreadRep::isCancellable() const
{
CLock lock(&s_mutex);
return (m_cancellable && !m_cancelling);
}
void* CThreadRep::getResult() const
{
// no lock necessary since thread isn't running
return m_result;
}
void* CThreadRep::getUserData() const
{
// no lock necessary because the value never changes
return m_userData;
}
CThreadRep* CThreadRep::getCurrentThreadRep()
{
#if defined(CONFIG_PTHREADS)
const pthread_t thread = pthread_self();
#elif defined(CONFIG_PLATFORM_WIN32)
const DWORD id = GetCurrentThreadId();
#endif
// lock list while we search
CLock lock(&s_mutex);
// search
CThreadRep* scan = s_head;
while (scan != NULL) {
#if defined(CONFIG_PTHREADS)
if (scan->m_thread == thread) {
break;
}
#elif defined(CONFIG_PLATFORM_WIN32)
if (scan->m_id == id) {
break;
}
#endif
scan = scan->m_next;
}
// create and use main thread rep if thread not found
if (scan == NULL) {
scan = new CThreadRep();
}
// ref for caller
++scan->m_refCount;
return scan;
}
void CThreadRep::doThreadFunc()
{
// default priority is slightly below normal
setPriority(1);
// wait for parent to initialize this object
{ CLock lock(&s_mutex); }
void* result = NULL;
try {
// go
m_job->run();
}
catch (XThreadCancel&) {
// client called cancel()
}
catch (XThreadExit& e) {
// client called exit()
result = e.m_result;
}
// note -- don't catch (...) to avoid masking bugs
// done with job
delete m_job;
// store exit result (no lock necessary because the result will
// not be accessed until m_exit is set)
m_result = result;
}
#if defined(CONFIG_PTHREADS)
#include "CStopwatch.h"
#include <time.h>
void CThreadRep::init()
{
m_result = NULL;
m_cancellable = true;
m_cancelling = false;
m_cancel = false;
m_exit = false;
}
void CThreadRep::fini()
{
// main thread has NULL job
if (m_job != NULL) {
pthread_detach(m_thread);
}
}
void CThreadRep::sleep(double timeout)
{
if (timeout < 0.0)
return;
struct timespec t;
t.tv_sec = (long)timeout;
t.tv_nsec = (long)(1000000000.0 * (timeout - (double)t.tv_sec));
nanosleep(&t, NULL);
}
void CThreadRep::cancel()
{
CLock lock(&s_mutex);
if (m_cancellable && !m_cancelling) {
m_cancel = true;
// break out of system calls
pthread_kill(m_thread, SIGALRM);
}
}
void CThreadRep::testCancel()
{
{
// prevent further cancellation
CLock lock(&s_mutex);
if (!m_cancel || !m_cancellable || m_cancelling)
return;
// update state for cancel
m_cancel = false;
m_cancelling = true;
}
// start cancel
throw XThreadCancel();
}
bool CThreadRep::wait(CThreadRep* target, double timeout)
{
if (target == this)
return false;
testCancel();
if (target->isExited())
return true;
if (timeout > 0.0) {
CStopwatch timer;
do {
sleep(0.05);
testCancel();
if (target->isExited())
return true;
} while (timer.getTime() <= timeout);
}
return false;
}
void CThreadRep::setPriority(int)
{
// FIXME
}
bool CThreadRep::isExited() const
{
CLock lock(&s_mutex);
return m_exit;
}
void* CThreadRep::threadFunc(void* arg)
{
CThreadRep* rep = (CThreadRep*)arg;
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
// run thread
rep->doThreadFunc();
// unref thread
rep->unref();
// mark as terminated
CLock lock(&s_mutex);
rep->m_exit = true;
// terminate the thread
return NULL;
}
void CThreadRep::threadCancel(int)
{
// do nothing
}
#elif defined(CONFIG_PLATFORM_WIN32)
#include <process.h>
void CThreadRep::init()
{
m_result = NULL;
m_cancellable = true;
m_cancelling = false;
m_exit = CreateEvent(NULL, TRUE, FALSE, NULL);
m_cancel = CreateEvent(NULL, TRUE, FALSE, NULL);
}
void CThreadRep::fini()
{
// destroy the events
CloseHandle(m_cancel);
CloseHandle(m_exit);
// close the handle (main thread has a NULL handle)
if (m_thread != NULL) {
CloseHandle(m_thread);
}
}
void CThreadRep::sleep(double timeout)
{
if (isCancellable())
WaitForSingleObject(m_cancel, (DWORD)(1000.0 * timeout));
else
::Sleep((DWORD)(1000.0 * timeout));
}
void CThreadRep::cancel()
{
SetEvent(m_cancel);
}
void CThreadRep::testCancel()
{
// poll cancel event. return if not set.
const DWORD result = ::WaitForSingleObject(getCancelEvent(), 0);
if (result != WAIT_OBJECT_0)
return;
{
// ignore if disabled or already cancelling
CLock lock(&s_mutex);
if (!m_cancellable || m_cancelling)
return;
// update state for cancel
m_cancelling = true;
ResetEvent(m_cancel);
}
// start cancel
throw XThreadCancel();
}
bool CThreadRep::wait(CThreadRep* target, double timeout)
{
// get the current thread. if it's the same as the target thread
// then the thread is waiting on itself.
CRefCountedPtr<CThreadRep> currentRep(CThreadRep::getCurrentThreadRep());
if (target == this)
return false;
// is cancellation enabled?
const DWORD n = (isCancellable() ? 2 : 1);
// convert timeout
DWORD t;
if (timeout < 0.0)
t = INFINITE;
else
t = (DWORD)(1000.0 * timeout);
// wait for this thread to be cancelled or for the target thread to
// terminate.
HANDLE handles[2];
handles[0] = target->getExitEvent();
handles[1] = m_cancel;
DWORD result = ::WaitForMultipleObjects(n, handles, FALSE, t);
// cancel takes priority
if (n == 2 && result != WAIT_OBJECT_0 + 1 &&
::WaitForSingleObject(handles[1], 0) == WAIT_OBJECT_0)
result = WAIT_OBJECT_0 + 1;
// handle result
switch (result) {
case WAIT_OBJECT_0 + 0:
// target thread terminated
return true;
case WAIT_OBJECT_0 + 1:
// this thread was cancelled. does not return.
testCancel();
default:
// error
return false;
}
}
void CThreadRep::setPriority(int n)
{
if (n < 0) {
switch (-n) {
case 1: n = THREAD_PRIORITY_ABOVE_NORMAL; break;
default: n = THREAD_PRIORITY_HIGHEST; break;
}
}
else {
switch (n) {
case 0: n = THREAD_PRIORITY_NORMAL; break;
case 1: n = THREAD_PRIORITY_BELOW_NORMAL; break;
case 2: n = THREAD_PRIORITY_LOWEST; break;
default: n = THREAD_PRIORITY_IDLE; break;
}
}
SetThreadPriority(m_thread, n);
}
HANDLE CThreadRep::getExitEvent() const
{
// no lock necessary because the value never changes
return m_exit;
}
HANDLE CThreadRep::getCancelEvent() const
{
// no lock necessary because the value never changes
return m_cancel;
}
unsigned int __stdcall CThreadRep::threadFunc(void* arg)
{
CThreadRep* rep = (CThreadRep*)arg;
// initialize OLE
const HRESULT hr = ::OleInitialize(NULL);
// run thread
rep->doThreadFunc();
// close OLE
if (!FAILED(hr)) {
OleUninitialize();
}
// signal termination
SetEvent(rep->m_exit);
// unref thread
rep->unref();
// terminate the thread
return 0;
}
#endif

122
mt/CThreadRep.h Normal file
View File

@@ -0,0 +1,122 @@
#ifndef CTHREADREP_H
#define CTHREADREP_H
#include "CMutex.h"
#include "BasicTypes.h"
#if defined(CONFIG_PTHREADS)
#include <pthread.h>
#elif defined(CONFIG_PLATFORM_WIN32)
#include <windows.h>
#endif
class IJob;
class CThreadRep {
public:
CThreadRep(IJob*, void* userData);
// manipulators
// change ref count
void ref();
void unref();
// the calling thread sleeps for t seconds. if t == 0.0 then
// the thread yields the CPU.
void sleep(double timeout);
// cancel the thread
void cancel();
// set cancellation state
bool enableCancel(bool enable);
// permanently disable further cancellation and start cancel cleanup
// if cancel has been called and cancellation hasn't been started yet.
void testCancel();
// wait for thread to exit or for current thread to cancel
bool wait(CThreadRep*, double timeout);
// set the priority
void setPriority(int n);
// accessors
// get the exit result for this thread. thread must be terminated.
void* getResult() const;
// get the user data passed to the constructor
void* getUserData() const;
// get the current cancellable state
bool isCancellable() const;
#if defined(CONFIG_PTHREADS)
bool isExited() const;
#elif defined(CONFIG_PLATFORM_WIN32)
HANDLE getExitEvent() const;
HANDLE getCancelEvent() const;
#endif
// return the thread rep for the calling thread. the returned
// rep has been ref()'d.
static CThreadRep* getCurrentThreadRep();
protected:
virtual ~CThreadRep();
private:
// internal constructor
CThreadRep();
// initialization/cleanup
void init();
void fini();
// thread rep lookup
static CThreadRep* find();
// thread functions
#if defined(CONFIG_PTHREADS)
static void* threadFunc(void* arg);
static void threadCancel(int);
#elif defined(CONFIG_PLATFORM_WIN32)
static unsigned int __stdcall threadFunc(void* arg);
#endif
void doThreadFunc();
// not implemented
CThreadRep(const CThreadRep&);
CThreadRep& operator=(const CThreadRep&);
private:
static CMutex s_mutex;
static CThreadRep* s_head;
CThreadRep* m_prev;
CThreadRep* m_next;
SInt32 m_refCount;
IJob* m_job;
void* m_userData;
void* m_result;
bool m_cancellable;
bool m_cancelling;
#if defined(CONFIG_PTHREADS)
pthread_t m_thread;
bool m_exit;
bool m_cancel;
#endif
#if defined(CONFIG_PLATFORM_WIN32)
HANDLE m_thread;
DWORD m_id;
HANDLE m_exit;
HANDLE m_cancel;
#endif
};
#endif

30
mt/CTimerThread.cpp Normal file
View File

@@ -0,0 +1,30 @@
#include "CTimerThread.h"
#include "CThread.h"
#include "TMethodJob.h"
#include <assert.h>
//
// CTimerThread
//
CTimerThread::CTimerThread(double timeout) : m_timeout(timeout)
{
assert(m_timeout > 0.0);
m_callingThread = new CThread(CThread::getCurrentThread());
m_timingThread = new CThread(new TMethodJob<CTimerThread>(
this, &CTimerThread::timer));
}
CTimerThread::~CTimerThread()
{
m_timingThread->cancel();
delete m_timingThread;
delete m_callingThread;
}
void CTimerThread::timer(void*)
{
CThread::sleep(m_timeout);
m_callingThread->cancel();
}

27
mt/CTimerThread.h Normal file
View File

@@ -0,0 +1,27 @@
#ifndef CTIMERTHREAD_H
#define CTIMERTHREAD_H
#include "common.h"
class CThread;
class CTimerThread {
public:
CTimerThread(double timeout);
~CTimerThread();
private:
void timer(void*);
// not implemented
CTimerThread(const CTimerThread&);
CTimerThread& operator=(const CTimerThread&);
private:
double m_timeout;
CThread* m_callingThread;
CThread* m_timingThread;
};
#endif

28
mt/Makefile Normal file
View File

@@ -0,0 +1,28 @@
DEPTH=..
include $(DEPTH)/Makecommon
#
# target file
#
TARGET = mt
#
# source files
#
LCXXINCS = \
-I$(DEPTH)/base \
$(NULL)
CXXFILES = \
CLock.cpp \
CMutex.cpp \
CCondVar.cpp \
CThread.cpp \
CThreadRep.cpp \
CTimerThread.cpp \
$(NULL)
targets: $(LIBTARGET)
$(LIBTARGET): $(OBJECTS)
if test ! -d $(LIBDIR); then $(MKDIR) $(LIBDIR); fi
$(ARF) $(LIBTARGET) $(OBJECTS)

31
mt/XThread.h Normal file
View File

@@ -0,0 +1,31 @@
#ifndef XTHREAD_H
#define XTHREAD_H
#include "common.h"
// generic thread exception
class XThread { };
// thrown by CThread::Exit() to exit a thread. clients of CThread
// must not throw this type but must rethrow it if caught (by
// XThreadExit, XThread, or ...).
class XThreadExit : public XThread {
public:
XThreadExit(void* result) : m_result(result) { }
~XThreadExit() { }
public:
void* m_result;
};
// thrown to cancel a thread. clients must not throw this type, but
// must rethrow it if caught (by XThreadCancel, XThread, or ...).
class XThreadCancel : public XThread { };
// convenience macro to rethrow an XThread exception but ignore other
// exceptions. put this in your catch (...) handler after necessary
// cleanup but before leaving or returning from the handler.
#define RETHROW_XTHREAD \
try { throw; } catch (XThread&) { throw; } catch (...) { }
#endif