mirror of
https://github.com/debauchee/barrier.git
synced 2026-12-01 08:15:25 +08:00
Reorganized source tree. Moved client.cpp into cmd/synergy as
synergy.cpp and server.cpp into cmd/synergyd as synergyd.cpp. Moved and renamed related files. Moved remaining source files into lib/.... Modified and added makefiles as appropriate. Result is that library files are under lib with each library in its own directory and program files are under cmd with each command in its own directory.
This commit is contained in:
315
lib/mt/CCondVar.cpp
Normal file
315
lib/mt/CCondVar.cpp
Normal file
@@ -0,0 +1,315 @@
|
||||
#include "CCondVar.h"
|
||||
#include "CStopwatch.h"
|
||||
|
||||
//
|
||||
// CCondVarBase
|
||||
//
|
||||
|
||||
CCondVarBase::CCondVarBase(CMutex* mutex) :
|
||||
m_mutex(mutex)
|
||||
#if WINDOWS_LIKE
|
||||
, m_waitCountMutex()
|
||||
#endif
|
||||
{
|
||||
assert(m_mutex != NULL);
|
||||
init();
|
||||
}
|
||||
|
||||
CCondVarBase::~CCondVarBase()
|
||||
{
|
||||
fini();
|
||||
}
|
||||
|
||||
void
|
||||
CCondVarBase::lock() const
|
||||
{
|
||||
m_mutex->lock();
|
||||
}
|
||||
|
||||
void
|
||||
CCondVarBase::unlock() const
|
||||
{
|
||||
m_mutex->unlock();
|
||||
}
|
||||
|
||||
bool
|
||||
CCondVarBase::wait(double timeout) const
|
||||
{
|
||||
CStopwatch timer(true);
|
||||
return wait(timer, timeout);
|
||||
}
|
||||
|
||||
CMutex*
|
||||
CCondVarBase::getMutex() const
|
||||
{
|
||||
return m_mutex;
|
||||
}
|
||||
|
||||
#if HAVE_PTHREAD
|
||||
|
||||
#include "CThread.h"
|
||||
#include <pthread.h>
|
||||
#include <sys/time.h>
|
||||
#include <cerrno>
|
||||
|
||||
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()
|
||||
{
|
||||
pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>(m_cond);
|
||||
int status = pthread_cond_signal(cond);
|
||||
assert(status == 0);
|
||||
}
|
||||
|
||||
void
|
||||
CCondVarBase::broadcast()
|
||||
{
|
||||
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 && status != EINTR) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
switch (status) {
|
||||
case 0:
|
||||
// success
|
||||
return true;
|
||||
|
||||
case ETIMEDOUT:
|
||||
return false;
|
||||
|
||||
default:
|
||||
assert(0 && "condition variable wait error");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#endif // HAVE_PTHREAD
|
||||
|
||||
#if WINDOWS_LIKE
|
||||
|
||||
#include "CLock.h"
|
||||
#include "CThreadRep.h"
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#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()
|
||||
{
|
||||
// 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()
|
||||
{
|
||||
// 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
|
||||
CThreadPtr 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 // WINDOWS_LIKE
|
||||
226
lib/mt/CCondVar.h
Normal file
226
lib/mt/CCondVar.h
Normal file
@@ -0,0 +1,226 @@
|
||||
#ifndef CCONDVAR_H
|
||||
#define CCONDVAR_H
|
||||
|
||||
#include "CMutex.h"
|
||||
#include "BasicTypes.h"
|
||||
|
||||
class CStopwatch;
|
||||
|
||||
//! Generic condition variable
|
||||
/*!
|
||||
This class provides functionality common to all condition variables
|
||||
but doesn't provide the actual variable storage. A condition variable
|
||||
is a multiprocessing primitive that can be waited on. Every condition
|
||||
variable has an associated mutex.
|
||||
*/
|
||||
class CCondVarBase {
|
||||
public:
|
||||
/*!
|
||||
\c mutex must not be NULL. All condition variables have an
|
||||
associated mutex. The mutex needn't be unique to one condition
|
||||
variable.
|
||||
*/
|
||||
CCondVarBase(CMutex* mutex);
|
||||
~CCondVarBase();
|
||||
|
||||
//! @name manipulators
|
||||
//@{
|
||||
|
||||
//! Lock the condition variable's mutex
|
||||
/*!
|
||||
Lock the condition variable's mutex. The condition variable should
|
||||
be locked before reading or writing it. It must be locked for a
|
||||
call to wait(). Locks are not recursive; locking a locked mutex
|
||||
will deadlock the thread.
|
||||
*/
|
||||
void lock() const;
|
||||
|
||||
//! Unlock the condition variable's mutex
|
||||
void unlock() const;
|
||||
|
||||
//! Signal the condition variable
|
||||
/*!
|
||||
Wake up one waiting thread, if there are any. Which thread gets
|
||||
woken is undefined.
|
||||
*/
|
||||
void signal();
|
||||
|
||||
//! Signal the condition variable
|
||||
/*!
|
||||
Wake up all waiting threads, if any.
|
||||
*/
|
||||
void broadcast();
|
||||
|
||||
//@}
|
||||
//! @name accessors
|
||||
//@{
|
||||
|
||||
//! Wait on the condition variable
|
||||
/*!
|
||||
Wait on the condition variable. If \c timeout < 0 then wait until
|
||||
signalled, otherwise up to \c timeout seconds or until signalled,
|
||||
whichever comes first. Returns true if the object was signalled
|
||||
during the wait, false otherwise.
|
||||
|
||||
The proper way to wait for a condition is:
|
||||
\code
|
||||
cv.lock();
|
||||
while (cv-expr) {
|
||||
cv.wait();
|
||||
}
|
||||
cv.unlock();
|
||||
\endcode
|
||||
where \c cv-expr involves the value of \c cv and is false when the
|
||||
condition is satisfied.
|
||||
|
||||
(cancellation point)
|
||||
*/
|
||||
bool wait(double timeout = -1.0) const;
|
||||
|
||||
//! Wait on the condition variable
|
||||
/*!
|
||||
Same as \c wait(double) but use \c timer to compare against \timeout.
|
||||
Since clients normally wait on condition variables in a loop, clients
|
||||
can use this to avoid recalculating \c timeout on each iteration.
|
||||
Passing a stopwatch with a negative \c timeout is pointless (it will
|
||||
never time out) but permitted.
|
||||
|
||||
(cancellation point)
|
||||
*/
|
||||
bool wait(CStopwatch& timer, double timeout) const;
|
||||
|
||||
//! Get the mutex
|
||||
/*!
|
||||
Get the mutex passed to the c'tor.
|
||||
*/
|
||||
CMutex* getMutex() const;
|
||||
|
||||
//@}
|
||||
|
||||
private:
|
||||
void init();
|
||||
void fini();
|
||||
|
||||
// not implemented
|
||||
CCondVarBase(const CCondVarBase&);
|
||||
CCondVarBase& operator=(const CCondVarBase&);
|
||||
|
||||
private:
|
||||
CMutex* m_mutex;
|
||||
void* m_cond;
|
||||
|
||||
#if WINDOWS_LIKE
|
||||
enum { kSignal, kBroadcast };
|
||||
mutable UInt32 m_waitCount;
|
||||
CMutex m_waitCountMutex;
|
||||
#endif
|
||||
};
|
||||
|
||||
//! Condition variable
|
||||
/*!
|
||||
A condition variable with storage for type \c T.
|
||||
*/
|
||||
template <class T>
|
||||
class CCondVar : public CCondVarBase {
|
||||
public:
|
||||
//! Initialize using \c value
|
||||
CCondVar(CMutex* mutex, const T& value);
|
||||
//! Initialize using another condition variable's value
|
||||
CCondVar(const CCondVar&);
|
||||
~CCondVar();
|
||||
|
||||
//! @name manipulators
|
||||
//@{
|
||||
|
||||
//! Assigns the value of \c cv to this
|
||||
/*!
|
||||
Set the variable's value. The condition variable should be locked
|
||||
before calling this method.
|
||||
*/
|
||||
CCondVar& operator=(const CCondVar& cv);
|
||||
|
||||
//! Assigns \c value to this
|
||||
/*!
|
||||
Set the variable's value. The condition variable should be locked
|
||||
before calling this method.
|
||||
*/
|
||||
CCondVar& operator=(const T& v);
|
||||
|
||||
//@}
|
||||
//! @name accessors
|
||||
//@{
|
||||
|
||||
//! Get the variable's value
|
||||
/*!
|
||||
Get the variable's value. The condition variable should be locked
|
||||
before calling this method.
|
||||
*/
|
||||
operator const T&() const;
|
||||
|
||||
//@}
|
||||
|
||||
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
|
||||
{
|
||||
return m_data;
|
||||
}
|
||||
|
||||
|
||||
// force instantiation of these common types
|
||||
template class CCondVar<bool>;
|
||||
template class CCondVar<SInt32>;
|
||||
|
||||
#endif
|
||||
24
lib/mt/CLock.cpp
Normal file
24
lib/mt/CLock.cpp
Normal file
@@ -0,0 +1,24 @@
|
||||
#include "CLock.h"
|
||||
#include "CCondVar.h"
|
||||
#include "CMutex.h"
|
||||
|
||||
//
|
||||
// CLock
|
||||
//
|
||||
|
||||
CLock::CLock(const CMutex* mutex) :
|
||||
m_mutex(mutex)
|
||||
{
|
||||
m_mutex->lock();
|
||||
}
|
||||
|
||||
CLock::CLock(const CCondVarBase* cv) :
|
||||
m_mutex(cv->getMutex())
|
||||
{
|
||||
m_mutex->lock();
|
||||
}
|
||||
|
||||
CLock::~CLock()
|
||||
{
|
||||
m_mutex->unlock();
|
||||
}
|
||||
32
lib/mt/CLock.h
Normal file
32
lib/mt/CLock.h
Normal file
@@ -0,0 +1,32 @@
|
||||
#ifndef CLOCK_H
|
||||
#define CLOCK_H
|
||||
|
||||
class CMutex;
|
||||
class CCondVarBase;
|
||||
|
||||
//! Mutual exclusion lock utility
|
||||
/*!
|
||||
This class locks a mutex or condition variable in the c'tor and unlocks
|
||||
it in the d'tor. It's easier and safer than manually locking and
|
||||
unlocking since unlocking must usually be done no matter how a function
|
||||
exits (including by unwinding due to an exception).
|
||||
*/
|
||||
class CLock {
|
||||
public:
|
||||
//! Lock the mutex \c mutex
|
||||
CLock(const CMutex* mutex);
|
||||
//! Lock the condition variable \c cv
|
||||
CLock(const CCondVarBase* cv);
|
||||
//! Unlock the mutex or condition variable
|
||||
~CLock();
|
||||
|
||||
private:
|
||||
// not implemented
|
||||
CLock(const CLock&);
|
||||
CLock& operator=(const CLock&);
|
||||
|
||||
private:
|
||||
const CMutex* m_mutex;
|
||||
};
|
||||
|
||||
#endif
|
||||
136
lib/mt/CMutex.cpp
Normal file
136
lib/mt/CMutex.cpp
Normal file
@@ -0,0 +1,136 @@
|
||||
#include "CMutex.h"
|
||||
#include "CLog.h"
|
||||
|
||||
//
|
||||
// CMutex
|
||||
//
|
||||
|
||||
CMutex::CMutex()
|
||||
{
|
||||
init();
|
||||
}
|
||||
|
||||
CMutex::CMutex(const CMutex&)
|
||||
{
|
||||
init();
|
||||
}
|
||||
|
||||
CMutex::~CMutex()
|
||||
{
|
||||
fini();
|
||||
}
|
||||
|
||||
CMutex&
|
||||
CMutex::operator=(const CMutex&)
|
||||
{
|
||||
return *this;
|
||||
}
|
||||
|
||||
#if HAVE_PTHREAD
|
||||
|
||||
#include <pthread.h>
|
||||
#include <cerrno>
|
||||
|
||||
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);
|
||||
logc(status != 0, (CLOG_ERR "pthread_mutex_destroy status %d", status));
|
||||
assert(status == 0);
|
||||
delete mutex;
|
||||
}
|
||||
|
||||
void
|
||||
CMutex::lock() const
|
||||
{
|
||||
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:
|
||||
log((CLOG_ERR "pthread_mutex_lock status %d", status));
|
||||
assert(0 && "unexpected error");
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
CMutex::unlock() const
|
||||
{
|
||||
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:
|
||||
log((CLOG_ERR "pthread_mutex_unlock status %d", status));
|
||||
assert(0 && "unexpected error");
|
||||
}
|
||||
}
|
||||
|
||||
#endif // HAVE_PTHREAD
|
||||
|
||||
#if WINDOWS_LIKE
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#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
|
||||
{
|
||||
EnterCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(m_mutex));
|
||||
}
|
||||
|
||||
void
|
||||
CMutex::unlock() const
|
||||
{
|
||||
LeaveCriticalSection(reinterpret_cast<CRITICAL_SECTION*>(m_mutex));
|
||||
}
|
||||
|
||||
#endif // WINDOWS_LIKE
|
||||
66
lib/mt/CMutex.h
Normal file
66
lib/mt/CMutex.h
Normal file
@@ -0,0 +1,66 @@
|
||||
#ifndef CMUTEX_H
|
||||
#define CMUTEX_H
|
||||
|
||||
//! Mutual exclusion
|
||||
/*!
|
||||
A non-recursive mutual exclusion object. Only one thread at a time can
|
||||
hold a lock on a mutex. Any thread that attempts to lock a locked mutex
|
||||
will block until the mutex is unlocked. At that time, if any threads are
|
||||
blocked, exactly one waiting thread will acquire the lock and continue
|
||||
running. A thread may not lock a mutex it already owns the lock on; if
|
||||
it tries it will deadlock itself.
|
||||
*/
|
||||
class CMutex {
|
||||
public:
|
||||
CMutex();
|
||||
//! Equivalent to default c'tor
|
||||
/*!
|
||||
Copy c'tor doesn't copy anything. It just makes it possible to
|
||||
copy objects that contain a mutex.
|
||||
*/
|
||||
CMutex(const CMutex&);
|
||||
~CMutex();
|
||||
|
||||
//! @name manipulators
|
||||
//@{
|
||||
|
||||
//! Does nothing
|
||||
/*!
|
||||
This does nothing. It just makes it possible to assign objects
|
||||
that contain a mutex.
|
||||
*/
|
||||
CMutex& operator=(const CMutex&);
|
||||
|
||||
//@}
|
||||
//! @name accessors
|
||||
//@{
|
||||
|
||||
//! Lock the mutex
|
||||
/*!
|
||||
Locks the mutex, which must not have been previously locked by the
|
||||
calling thread. This blocks if the mutex is already locked by another
|
||||
thread.
|
||||
|
||||
(cancellation point)
|
||||
*/
|
||||
void lock() const;
|
||||
|
||||
//! Unlock the mutex
|
||||
/*!
|
||||
Unlocks the mutex, which must have been previously locked by the
|
||||
calling thread.
|
||||
*/
|
||||
void unlock() const;
|
||||
|
||||
//@}
|
||||
|
||||
private:
|
||||
void init();
|
||||
void fini();
|
||||
|
||||
private:
|
||||
friend class CCondVarBase;
|
||||
void* m_mutex;
|
||||
};
|
||||
|
||||
#endif
|
||||
159
lib/mt/CThread.cpp
Normal file
159
lib/mt/CThread.cpp
Normal file
@@ -0,0 +1,159 @@
|
||||
#include "CThread.h"
|
||||
#include "CLock.h"
|
||||
#include "CThreadRep.h"
|
||||
#include "XThread.h"
|
||||
#include "CLog.h"
|
||||
#include "CStopwatch.h"
|
||||
|
||||
//
|
||||
// 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::init()
|
||||
{
|
||||
CThreadRep::initThreads();
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
CThreadPtr currentRep(CThreadRep::getCurrentThreadRep());
|
||||
log((CLOG_DEBUG1 "throw exit on thread %p", currentRep.operator->()));
|
||||
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);
|
||||
}
|
||||
|
||||
#if WINDOWS_LIKE
|
||||
bool
|
||||
CThread::waitForEvent(double timeout)
|
||||
{
|
||||
CThreadPtr currentRep(CThreadRep::getCurrentThreadRep());
|
||||
return currentRep->waitForEvent(timeout);
|
||||
}
|
||||
#endif
|
||||
|
||||
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()
|
||||
{
|
||||
return m_rep->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);
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// CThreadMaskCancel
|
||||
//
|
||||
|
||||
CThreadMaskCancel::CThreadMaskCancel() :
|
||||
m_old(CThread::enableCancel(false))
|
||||
{
|
||||
// do nothing
|
||||
}
|
||||
|
||||
CThreadMaskCancel::~CThreadMaskCancel()
|
||||
{
|
||||
CThread::enableCancel(m_old);
|
||||
}
|
||||
243
lib/mt/CThread.h
Normal file
243
lib/mt/CThread.h
Normal file
@@ -0,0 +1,243 @@
|
||||
#ifndef CTHREAD_H
|
||||
#define CTHREAD_H
|
||||
|
||||
#include "common.h"
|
||||
|
||||
class IJob;
|
||||
class CThreadRep;
|
||||
|
||||
//! Thread handle
|
||||
/*!
|
||||
Creating a CThread creates a new context of execution (i.e. thread) that
|
||||
runs simulatenously with the calling thread. A CThread is only a handle
|
||||
to a thread; deleting a CThread does not cancel or destroy the thread it
|
||||
refers to and multiple CThread objects can refer to the same thread.
|
||||
|
||||
Threads can terminate themselves but cannot be forced to terminate by
|
||||
other threads. However, other threads can signal a thread to terminate
|
||||
itself by cancelling it. And a thread can wait (block) on another thread
|
||||
to terminate.
|
||||
|
||||
Most functions that can block for an arbitrary time are cancellation
|
||||
points. A cancellation point is a function that can be interrupted by
|
||||
a request to cancel the thread. Cancellation points are noted in the
|
||||
documentation.
|
||||
*/
|
||||
// note -- do not derive from this class
|
||||
class CThread {
|
||||
public:
|
||||
//! Run \c adoptedJob in a new thread
|
||||
/*!
|
||||
Create and start a new thread executing the \c adoptedJob. The
|
||||
user data can be retrieved with getUserData(). The new thread
|
||||
takes ownership of \c adoptedJob and will delete it.
|
||||
*/
|
||||
CThread(IJob* adoptedJob, void* userData = 0);
|
||||
|
||||
//! Duplicate a thread handle
|
||||
/*!
|
||||
Make a new thread object that refers to an existing thread.
|
||||
This does \b not start a new thread.
|
||||
*/
|
||||
CThread(const CThread&);
|
||||
|
||||
//! Release a thread handle
|
||||
/*!
|
||||
Release a thread handle. This does not terminate the thread. A thread
|
||||
will keep running until the job completes or calls exit() or allows
|
||||
itself to be cancelled.
|
||||
*/
|
||||
~CThread();
|
||||
|
||||
//! @name manipulators
|
||||
//@{
|
||||
|
||||
//! Assign thread handle
|
||||
/*!
|
||||
Assign a thread handle. This has no effect on the threads, it simply
|
||||
makes this thread object refer to another thread. It does \b not
|
||||
start a new thread.
|
||||
*/
|
||||
CThread& operator=(const CThread&);
|
||||
|
||||
//! Initialize the thread library
|
||||
/*!
|
||||
Initialize the thread library. This \b must be called before
|
||||
any other thread methods or creating a thread object. It is
|
||||
harmless to call init() multiple times.
|
||||
*/
|
||||
static void init();
|
||||
|
||||
//! Sleep
|
||||
/*!
|
||||
Blocks the calling thread for \c timeout seconds. If
|
||||
\c timeout < 0.0 then the call returns immediately. If \c timeout
|
||||
== 0.0 then the calling thread yields the CPU.
|
||||
|
||||
(cancellation point)
|
||||
*/
|
||||
static void sleep(double timeout);
|
||||
|
||||
//! Terminate the calling thread
|
||||
/*!
|
||||
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 \c catch(...) blocks then you should add the following before
|
||||
each to avoid catching the exit:
|
||||
\code
|
||||
catch(CThreadExit&) { throw; }
|
||||
\endcode
|
||||
or add the \c RETHROW_XTHREAD macro to the \c catch(...) block.
|
||||
*/
|
||||
static void exit(void*);
|
||||
|
||||
//! Enable or disable cancellation
|
||||
/*!
|
||||
Enable or disable cancellation. The default is enabled. This is not
|
||||
a cancellation point so if you just enabled cancellation and want to
|
||||
allow immediate cancellation you need to call testCancel().
|
||||
Returns the previous state.
|
||||
*/
|
||||
static bool enableCancel(bool);
|
||||
|
||||
//! Cancel thread
|
||||
/*!
|
||||
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 unlock and clean up any resources they
|
||||
may have, especially mutexes. They can \c 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 (like CLock). 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 \c catch(XThreadCancel) must always rethrow the
|
||||
exception. Clients that \c catch(...) must either rethrow the
|
||||
exception or include a \c catch(XThreadCancel) handler that
|
||||
rethrows. The \c RETHROW_XTHREAD macro may be useful for that.
|
||||
*/
|
||||
void cancel();
|
||||
|
||||
//! Change thread priority
|
||||
/*!
|
||||
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 permitted and will be silenty ignored.
|
||||
*/
|
||||
void setPriority(int n);
|
||||
|
||||
//@}
|
||||
//! @name accessors
|
||||
//@{
|
||||
|
||||
//! Get current thread's handle
|
||||
/*!
|
||||
Return a CThread object representing the calling thread.
|
||||
*/
|
||||
static CThread getCurrentThread();
|
||||
|
||||
//! Test for cancellation
|
||||
/*!
|
||||
testCancel() does nothing but is a cancellation point. Call
|
||||
this to make a function itself a cancellation point. If the
|
||||
thread was cancelled and cancellation is enabled this will
|
||||
cause the thread to unwind the stack and terminate.
|
||||
|
||||
(cancellation point)
|
||||
*/
|
||||
static void testCancel();
|
||||
|
||||
//! Get the thread user data
|
||||
/*!
|
||||
Gets the user data passed to the c'tor that created this thread.
|
||||
*/
|
||||
void* getUserData();
|
||||
|
||||
//! Wait for thread to terminate
|
||||
/*!
|
||||
Waits for the thread to terminate (by exit() or cancel() or
|
||||
by returning from the thread job) for up to \c timeout seconds,
|
||||
returning true if the thread terminated and false otherwise.
|
||||
This returns immediately with false if called by a thread on
|
||||
itself and immediately with true if the thread has already
|
||||
terminated. This will wait forever if \c timeout < 0.0.
|
||||
|
||||
(cancellation point)
|
||||
*/
|
||||
bool wait(double timeout = -1.0) const;
|
||||
|
||||
#if WINDOWS_LIKE
|
||||
//! Wait for an event (win32)
|
||||
/*!
|
||||
Wait for the message queue to contain a message for up to \c timeout
|
||||
seconds. This returns immediately if any message is available
|
||||
(including messages that were already in the queue during the last
|
||||
call to \c GetMessage() or \c PeekMessage() or waitForEvent().
|
||||
Returns true iff a message is available. This will wait forever
|
||||
if \c timeout < 0.0.
|
||||
|
||||
This method is available under win32 only.
|
||||
|
||||
(cancellation point)
|
||||
*/
|
||||
static bool waitForEvent(double timeout = -1.0);
|
||||
#endif
|
||||
|
||||
//! Get the exit result
|
||||
/*!
|
||||
Returns the exit result. This does an implicit wait(). It returns
|
||||
NULL immediately if called by a thread on itself or on a thread that
|
||||
was cancelled.
|
||||
|
||||
(cancellation point)
|
||||
*/
|
||||
void* getResult() const;
|
||||
|
||||
//! Compare thread handles
|
||||
/*!
|
||||
Returns true if two CThread objects refer to the same thread.
|
||||
*/
|
||||
bool operator==(const CThread&) const;
|
||||
|
||||
//! Compare thread handles
|
||||
/*!
|
||||
Returns true if two CThread objects do not refer to the same thread.
|
||||
*/
|
||||
bool operator!=(const CThread&) const;
|
||||
|
||||
//@}
|
||||
|
||||
private:
|
||||
CThread(CThreadRep*);
|
||||
|
||||
private:
|
||||
CThreadRep* m_rep;
|
||||
};
|
||||
|
||||
//! Disable cancellation utility
|
||||
/*!
|
||||
This class disables cancellation for the current thread in the c'tor
|
||||
and enables it in the d'tor.
|
||||
*/
|
||||
class CThreadMaskCancel {
|
||||
public:
|
||||
CThreadMaskCancel();
|
||||
~CThreadMaskCancel();
|
||||
|
||||
private:
|
||||
bool m_old;
|
||||
};
|
||||
|
||||
#endif
|
||||
737
lib/mt/CThreadRep.cpp
Normal file
737
lib/mt/CThreadRep.cpp
Normal file
@@ -0,0 +1,737 @@
|
||||
#include "CThreadRep.h"
|
||||
#include "CLock.h"
|
||||
#include "CMutex.h"
|
||||
#include "CThread.h"
|
||||
#include "XThread.h"
|
||||
#include "CLog.h"
|
||||
#include "IJob.h"
|
||||
|
||||
#if HAVE_PTHREAD
|
||||
|
||||
# include <signal.h>
|
||||
# define SIGWAKEUP SIGUSR1
|
||||
|
||||
#elif WINDOWS_LIKE
|
||||
|
||||
# if !defined(_MT)
|
||||
# error multithreading compile option is required
|
||||
# endif
|
||||
# include <process.h>
|
||||
|
||||
#else
|
||||
|
||||
#error unsupported platform for multithreading
|
||||
|
||||
#endif
|
||||
|
||||
// FIXME -- temporary exception type
|
||||
class XThreadUnavailable { };
|
||||
|
||||
//
|
||||
// CThreadRep
|
||||
//
|
||||
|
||||
CMutex* CThreadRep::s_mutex = NULL;
|
||||
CThreadRep* CThreadRep::s_head = NULL;
|
||||
#if HAVE_PTHREAD
|
||||
pthread_t CThreadRep::s_signalThread;
|
||||
#endif
|
||||
|
||||
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
|
||||
assert(s_mutex != NULL);
|
||||
|
||||
// initialize stuff
|
||||
init();
|
||||
#if HAVE_PTHREAD
|
||||
// get main thread id
|
||||
m_thread = pthread_self();
|
||||
#elif WINDOWS_LIKE
|
||||
// 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);
|
||||
assert(s_mutex != 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 HAVE_PTHREAD
|
||||
// mask some signals in all threads except the main thread
|
||||
sigset_t sigset, oldsigset;
|
||||
sigemptyset(&sigset);
|
||||
sigaddset(&sigset, SIGINT);
|
||||
sigaddset(&sigset, SIGTERM);
|
||||
pthread_sigmask(SIG_BLOCK, &sigset, &oldsigset);
|
||||
int status = pthread_create(&m_thread, NULL, threadFunc, (void*)this);
|
||||
pthread_sigmask(SIG_SETMASK, &oldsigset, NULL);
|
||||
if (status != 0) {
|
||||
throw XThreadUnavailable();
|
||||
}
|
||||
#elif WINDOWS_LIKE
|
||||
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::initThreads()
|
||||
{
|
||||
if (s_mutex == NULL) {
|
||||
s_mutex = new CMutex;
|
||||
|
||||
#if HAVE_PTHREAD
|
||||
// install SIGWAKEUP handler
|
||||
struct sigaction act;
|
||||
sigemptyset(&act.sa_mask);
|
||||
# if defined(SA_INTERRUPT)
|
||||
act.sa_flags = SA_INTERRUPT;
|
||||
# else
|
||||
act.sa_flags = 0;
|
||||
# endif
|
||||
act.sa_handler = &threadCancel;
|
||||
sigaction(SIGWAKEUP, &act, NULL);
|
||||
|
||||
// set signal mask
|
||||
sigset_t sigset;
|
||||
sigemptyset(&sigset);
|
||||
sigaddset(&sigset, SIGWAKEUP);
|
||||
pthread_sigmask(SIG_UNBLOCK, &sigset, NULL);
|
||||
sigemptyset(&sigset);
|
||||
sigaddset(&sigset, SIGPIPE);
|
||||
sigaddset(&sigset, SIGINT);
|
||||
sigaddset(&sigset, SIGTERM);
|
||||
pthread_sigmask(SIG_BLOCK, &sigset, NULL);
|
||||
|
||||
// fire up the INT and TERM signal handler thread. we could
|
||||
// instead arrange to catch and handle these signals but
|
||||
// we'd be unable to cancel the main thread since no pthread
|
||||
// calls are allowed in a signal handler.
|
||||
int status = pthread_create(&s_signalThread, NULL,
|
||||
&CThreadRep::threadSignalHandler,
|
||||
getCurrentThreadRep());
|
||||
if (status != 0) {
|
||||
// can't create thread to wait for signal so don't block
|
||||
// the signals.
|
||||
sigemptyset(&sigset);
|
||||
sigaddset(&sigset, SIGINT);
|
||||
sigaddset(&sigset, SIGTERM);
|
||||
pthread_sigmask(SIG_UNBLOCK, &sigset, NULL);
|
||||
}
|
||||
#endif // HAVE_PTHREAD
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
assert(s_mutex != NULL);
|
||||
|
||||
#if HAVE_PTHREAD
|
||||
const pthread_t thread = pthread_self();
|
||||
#elif WINDOWS_LIKE
|
||||
const DWORD id = GetCurrentThreadId();
|
||||
#endif
|
||||
|
||||
// lock list while we search
|
||||
CLock lock(s_mutex);
|
||||
|
||||
// search
|
||||
CThreadRep* scan = s_head;
|
||||
while (scan != NULL) {
|
||||
#if HAVE_PTHREAD
|
||||
if (scan->m_thread == thread) {
|
||||
break;
|
||||
}
|
||||
#elif WINDOWS_LIKE
|
||||
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
|
||||
log((CLOG_DEBUG1 "thread %p entry", this));
|
||||
m_job->run();
|
||||
log((CLOG_DEBUG1 "thread %p exit", this));
|
||||
}
|
||||
|
||||
catch (XThreadCancel&) {
|
||||
// client called cancel()
|
||||
log((CLOG_DEBUG1 "caught cancel on thread %p", this));
|
||||
}
|
||||
|
||||
catch (XThreadExit& e) {
|
||||
// client called exit()
|
||||
result = e.m_result;
|
||||
log((CLOG_DEBUG1 "caught exit on thread %p", this));
|
||||
}
|
||||
catch (...) {
|
||||
log((CLOG_DEBUG1 "exception on thread %p", this));
|
||||
// note -- don't catch (...) to avoid masking bugs
|
||||
delete m_job;
|
||||
throw;
|
||||
}
|
||||
|
||||
// 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 HAVE_PTHREAD
|
||||
|
||||
#include "CStopwatch.h"
|
||||
#if TIME_WITH_SYS_TIME
|
||||
# include <sys/time.h>
|
||||
# include <time.h>
|
||||
#else
|
||||
# if HAVE_SYS_TIME_H
|
||||
# include <sys/time.h>
|
||||
# else
|
||||
# include <time.h>
|
||||
# endif
|
||||
#endif
|
||||
|
||||
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));
|
||||
while (nanosleep(&t, &t) < 0)
|
||||
testCancel();
|
||||
}
|
||||
|
||||
void
|
||||
CThreadRep::cancel()
|
||||
{
|
||||
CLock lock(s_mutex);
|
||||
if (m_cancellable && !m_cancelling) {
|
||||
m_cancel = true;
|
||||
}
|
||||
else {
|
||||
return;
|
||||
}
|
||||
|
||||
// break out of system calls
|
||||
log((CLOG_DEBUG1 "cancel thread %p", this));
|
||||
pthread_kill(m_thread, SIGWAKEUP);
|
||||
}
|
||||
|
||||
void
|
||||
CThreadRep::testCancel()
|
||||
{
|
||||
{
|
||||
CLock lock(s_mutex);
|
||||
|
||||
// done if not cancelled, not cancellable, or already cancelling
|
||||
if (!m_cancel || !m_cancellable || m_cancelling) {
|
||||
return;
|
||||
}
|
||||
|
||||
// update state for cancel
|
||||
m_cancel = false;
|
||||
m_cancelling = true;
|
||||
}
|
||||
|
||||
// start cancel
|
||||
log((CLOG_DEBUG1 "throw cancel on thread %p", this));
|
||||
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 (timeout < 0.0 || 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();
|
||||
|
||||
{
|
||||
// mark as terminated
|
||||
CLock lock(s_mutex);
|
||||
rep->m_exit = true;
|
||||
}
|
||||
|
||||
// unref thread
|
||||
rep->unref();
|
||||
|
||||
// terminate the thread
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void
|
||||
CThreadRep::threadCancel(int)
|
||||
{
|
||||
// do nothing
|
||||
}
|
||||
|
||||
void*
|
||||
CThreadRep::threadSignalHandler(void* vrep)
|
||||
{
|
||||
CThreadRep* mainThreadRep = reinterpret_cast<CThreadRep*>(vrep);
|
||||
|
||||
// detach
|
||||
pthread_detach(pthread_self());
|
||||
|
||||
// add signal to mask
|
||||
sigset_t sigset;
|
||||
sigemptyset(&sigset);
|
||||
sigaddset(&sigset, SIGINT);
|
||||
sigaddset(&sigset, SIGTERM);
|
||||
|
||||
// also wait on SIGABRT. on linux (others?) this thread (process)
|
||||
// will persist after all the other threads evaporate due to an
|
||||
// assert unless we wait on SIGABRT. that means our resources (like
|
||||
// the socket we're listening on) are not released and never will be
|
||||
// until the lingering thread is killed. i don't know why sigwait()
|
||||
// should protect the thread from being killed. note that sigwait()
|
||||
// doesn't actually return if we receive SIGABRT and, for some
|
||||
// reason, we don't have to block SIGABRT.
|
||||
sigaddset(&sigset, SIGABRT);
|
||||
|
||||
// we exit the loop via thread cancellation in sigwait()
|
||||
for (;;) {
|
||||
// wait
|
||||
int signal;
|
||||
sigwait(&sigset, &signal);
|
||||
|
||||
// if we get here then the signal was raised. cancel the thread.
|
||||
mainThreadRep->cancel();
|
||||
}
|
||||
}
|
||||
|
||||
#endif // HAVE_PTHREAD
|
||||
|
||||
#if WINDOWS_LIKE
|
||||
|
||||
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()
|
||||
{
|
||||
log((CLOG_DEBUG1 "cancel thread %p", this));
|
||||
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
|
||||
log((CLOG_DEBUG1 "throw cancel on thread %p", this));
|
||||
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.
|
||||
CThreadPtr 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:
|
||||
// timeout or error
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
CThreadRep::waitForEvent(double timeout)
|
||||
{
|
||||
// check if messages are available first. if we don't do this then
|
||||
// MsgWaitForMultipleObjects() will block even if the queue isn't
|
||||
// empty if the messages in the queue were there before the last
|
||||
// call to GetMessage()/PeekMessage().
|
||||
if (HIWORD(GetQueueStatus(QS_ALLINPUT)) != 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// is cancellation enabled?
|
||||
const DWORD n = (isCancellable() ? 1 : 0);
|
||||
|
||||
// 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[1];
|
||||
handles[0] = m_cancel;
|
||||
DWORD result = MsgWaitForMultipleObjects(n, handles, FALSE, t, QS_ALLINPUT);
|
||||
|
||||
// handle result
|
||||
switch (result) {
|
||||
case WAIT_OBJECT_0 + 1:
|
||||
// message is available
|
||||
return true;
|
||||
|
||||
case WAIT_OBJECT_0 + 0:
|
||||
// this thread was cancelled. does not return.
|
||||
testCancel();
|
||||
|
||||
default:
|
||||
// timeout or error
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
CThreadRep::setPriority(int n)
|
||||
{
|
||||
DWORD pClass = NORMAL_PRIORITY_CLASS;
|
||||
if (n < 0) {
|
||||
switch (-n) {
|
||||
case 1: n = THREAD_PRIORITY_ABOVE_NORMAL; break;
|
||||
case 2: n = THREAD_PRIORITY_HIGHEST; break;
|
||||
default:
|
||||
pClass = HIGH_PRIORITY_CLASS;
|
||||
switch (-n - 3) {
|
||||
case 0: n = THREAD_PRIORITY_LOWEST; break;
|
||||
case 1: n = THREAD_PRIORITY_BELOW_NORMAL; break;
|
||||
case 2: n = THREAD_PRIORITY_NORMAL; break;
|
||||
case 3: n = THREAD_PRIORITY_ABOVE_NORMAL; break;
|
||||
default: n = THREAD_PRIORITY_HIGHEST; break;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
SetPriorityClass(m_thread, pClass);
|
||||
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;
|
||||
|
||||
// run thread
|
||||
rep->doThreadFunc();
|
||||
|
||||
// signal termination
|
||||
SetEvent(rep->m_exit);
|
||||
|
||||
// unref thread
|
||||
rep->unref();
|
||||
|
||||
// terminate the thread
|
||||
return 0;
|
||||
}
|
||||
|
||||
#endif // WINDOWS_LIKE
|
||||
154
lib/mt/CThreadRep.h
Normal file
154
lib/mt/CThreadRep.h
Normal file
@@ -0,0 +1,154 @@
|
||||
#ifndef CTHREADREP_H
|
||||
#define CTHREADREP_H
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#if HAVE_PTHREAD
|
||||
#include <pthread.h>
|
||||
#elif WINDOWS_LIKE
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
class CMutex;
|
||||
class IJob;
|
||||
|
||||
//! Internal thread class; do not use directly
|
||||
class CThreadRep {
|
||||
public:
|
||||
CThreadRep(IJob*, void* userData);
|
||||
|
||||
// manipulators
|
||||
|
||||
// initialize the thread library
|
||||
static void initThreads();
|
||||
|
||||
// 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);
|
||||
|
||||
#if WINDOWS_LIKE
|
||||
// wait for a message on the queue
|
||||
bool waitForEvent(double timeout);
|
||||
#endif
|
||||
|
||||
// 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 HAVE_PTHREAD
|
||||
bool isExited() const;
|
||||
#elif WINDOWS_LIKE
|
||||
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 HAVE_PTHREAD
|
||||
static void* threadFunc(void* arg);
|
||||
static void threadCancel(int);
|
||||
static void* threadSignalHandler(void*);
|
||||
#elif WINDOWS_LIKE
|
||||
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;
|
||||
|
||||
int m_refCount;
|
||||
IJob* m_job;
|
||||
void* m_userData;
|
||||
void* m_result;
|
||||
bool m_cancellable;
|
||||
bool m_cancelling;
|
||||
|
||||
#if HAVE_PTHREAD
|
||||
pthread_t m_thread;
|
||||
bool m_exit;
|
||||
bool m_cancel;
|
||||
static pthread_t s_signalThread;
|
||||
#endif
|
||||
|
||||
#if WINDOWS_LIKE
|
||||
HANDLE m_thread;
|
||||
DWORD m_id;
|
||||
HANDLE m_exit;
|
||||
HANDLE m_cancel;
|
||||
#endif
|
||||
};
|
||||
|
||||
//
|
||||
// CThreadPtr -- auto unref'ing pointer to thread rep
|
||||
//
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
#endif
|
||||
42
lib/mt/CTimerThread.cpp
Normal file
42
lib/mt/CTimerThread.cpp
Normal file
@@ -0,0 +1,42 @@
|
||||
#include "CTimerThread.h"
|
||||
#include "CThread.h"
|
||||
#include "TMethodJob.h"
|
||||
#include "CLog.h"
|
||||
|
||||
//
|
||||
// CTimerThread
|
||||
//
|
||||
|
||||
CTimerThread::CTimerThread(double timeout) : m_timeout(timeout)
|
||||
{
|
||||
if (m_timeout >= 0.0) {
|
||||
m_callingThread = new CThread(CThread::getCurrentThread());
|
||||
m_timingThread = new CThread(new TMethodJob<CTimerThread>(
|
||||
this, &CTimerThread::timer));
|
||||
}
|
||||
else {
|
||||
m_callingThread = NULL;
|
||||
m_timingThread = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
CTimerThread::~CTimerThread()
|
||||
{
|
||||
if (m_timingThread != NULL) {
|
||||
log((CLOG_DEBUG1 "cancelling timeout"));
|
||||
m_timingThread->cancel();
|
||||
m_timingThread->wait();
|
||||
log((CLOG_DEBUG1 "cancelled timeout"));
|
||||
delete m_timingThread;
|
||||
delete m_callingThread;
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
CTimerThread::timer(void*)
|
||||
{
|
||||
log((CLOG_DEBUG1 "timeout in %f seconds", m_timeout));
|
||||
CThread::sleep(m_timeout);
|
||||
log((CLOG_DEBUG1 "timeout"));
|
||||
m_callingThread->cancel();
|
||||
}
|
||||
37
lib/mt/CTimerThread.h
Normal file
37
lib/mt/CTimerThread.h
Normal file
@@ -0,0 +1,37 @@
|
||||
#ifndef CTIMERTHREAD_H
|
||||
#define CTIMERTHREAD_H
|
||||
|
||||
class CThread;
|
||||
|
||||
//! A timer thread
|
||||
/*!
|
||||
An object of this class cancels the thread that called the c'tor unless
|
||||
the object is destroyed before a given timeout.
|
||||
*/
|
||||
class CTimerThread {
|
||||
public:
|
||||
//! Cancel calling thread after \c timeout seconds
|
||||
/*!
|
||||
Cancels the calling thread after \c timeout seconds unless destroyed
|
||||
before then. If \c timeout is less than zero then it never times
|
||||
out and this is a no-op.
|
||||
*/
|
||||
CTimerThread(double timeout);
|
||||
//! Cancel the timer thread
|
||||
~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
|
||||
|
||||
23
lib/mt/Makefile.am
Normal file
23
lib/mt/Makefile.am
Normal file
@@ -0,0 +1,23 @@
|
||||
## Process this file with automake to produce Makefile.in
|
||||
NULL =
|
||||
DEPTH = ../..
|
||||
|
||||
noinst_LIBRARIES = libmt.a
|
||||
libmt_a_SOURCES = \
|
||||
CLock.cpp \
|
||||
CMutex.cpp \
|
||||
CCondVar.cpp \
|
||||
CThread.cpp \
|
||||
CThreadRep.cpp \
|
||||
CTimerThread.cpp \
|
||||
CCondVar.h \
|
||||
CLock.h \
|
||||
CMutex.h \
|
||||
CThread.h \
|
||||
CThreadRep.h \
|
||||
CTimerThread.h \
|
||||
XThread.h \
|
||||
$(NULL)
|
||||
INCLUDES = \
|
||||
-I$(DEPTH)/lib/base \
|
||||
$(NULL)
|
||||
39
lib/mt/XThread.h
Normal file
39
lib/mt/XThread.h
Normal file
@@ -0,0 +1,39 @@
|
||||
#ifndef XTHREAD_H
|
||||
#define XTHREAD_H
|
||||
|
||||
//! Generic thread exception
|
||||
class XThread { };
|
||||
|
||||
//! Thread exception to exit
|
||||
/*!
|
||||
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:
|
||||
//! \c result is the result of the thread
|
||||
XThreadExit(void* result) : m_result(result) { }
|
||||
~XThreadExit() { }
|
||||
|
||||
public:
|
||||
void* m_result;
|
||||
};
|
||||
|
||||
//! Thread exception to cancel
|
||||
/*!
|
||||
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 { };
|
||||
|
||||
/*!
|
||||
\def RETHROW_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
|
||||
146
lib/mt/mt.dsp
Normal file
146
lib/mt/mt.dsp
Normal file
@@ -0,0 +1,146 @@
|
||||
# Microsoft Developer Studio Project File - Name="mt" - Package Owner=<4>
|
||||
# Microsoft Developer Studio Generated Build File, Format Version 6.00
|
||||
# ** DO NOT EDIT **
|
||||
|
||||
# TARGTYPE "Win32 (x86) Static Library" 0x0104
|
||||
|
||||
CFG=mt - Win32 Debug
|
||||
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
|
||||
!MESSAGE use the Export Makefile command and run
|
||||
!MESSAGE
|
||||
!MESSAGE NMAKE /f "mt.mak".
|
||||
!MESSAGE
|
||||
!MESSAGE You can specify a configuration when running NMAKE
|
||||
!MESSAGE by defining the macro CFG on the command line. For example:
|
||||
!MESSAGE
|
||||
!MESSAGE NMAKE /f "mt.mak" CFG="mt - Win32 Debug"
|
||||
!MESSAGE
|
||||
!MESSAGE Possible choices for configuration are:
|
||||
!MESSAGE
|
||||
!MESSAGE "mt - Win32 Release" (based on "Win32 (x86) Static Library")
|
||||
!MESSAGE "mt - Win32 Debug" (based on "Win32 (x86) Static Library")
|
||||
!MESSAGE
|
||||
|
||||
# Begin Project
|
||||
# PROP AllowPerConfigDependencies 0
|
||||
# PROP Scc_ProjName ""
|
||||
# PROP Scc_LocalPath ""
|
||||
CPP=cl.exe
|
||||
RSC=rc.exe
|
||||
|
||||
!IF "$(CFG)" == "mt - Win32 Release"
|
||||
|
||||
# PROP BASE Use_MFC 0
|
||||
# PROP BASE Use_Debug_Libraries 0
|
||||
# PROP BASE Output_Dir "Release"
|
||||
# PROP BASE Intermediate_Dir "Release"
|
||||
# PROP BASE Target_Dir ""
|
||||
# PROP Use_MFC 0
|
||||
# PROP Use_Debug_Libraries 0
|
||||
# PROP Output_Dir "Release"
|
||||
# PROP Intermediate_Dir "Release"
|
||||
# PROP Target_Dir ""
|
||||
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
|
||||
# ADD CPP /nologo /MT /W4 /GX /O2 /I "..\base" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /FD /c
|
||||
# SUBTRACT CPP /YX
|
||||
# ADD BASE RSC /l 0x409 /d "NDEBUG"
|
||||
# ADD RSC /l 0x409 /d "NDEBUG"
|
||||
BSC32=bscmake.exe
|
||||
# ADD BASE BSC32 /nologo
|
||||
# ADD BSC32 /nologo
|
||||
LIB32=link.exe -lib
|
||||
# ADD BASE LIB32 /nologo
|
||||
# ADD LIB32 /nologo
|
||||
|
||||
!ELSEIF "$(CFG)" == "mt - Win32 Debug"
|
||||
|
||||
# PROP BASE Use_MFC 0
|
||||
# PROP BASE Use_Debug_Libraries 1
|
||||
# PROP BASE Output_Dir "Debug"
|
||||
# PROP BASE Intermediate_Dir "Debug"
|
||||
# PROP BASE Target_Dir ""
|
||||
# PROP Use_MFC 0
|
||||
# PROP Use_Debug_Libraries 1
|
||||
# PROP Output_Dir "Debug"
|
||||
# PROP Intermediate_Dir "Debug"
|
||||
# PROP Target_Dir ""
|
||||
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
|
||||
# ADD CPP /nologo /MTd /W4 /Gm /GX /ZI /Od /I "..\base" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FD /GZ /c
|
||||
# SUBTRACT CPP /YX
|
||||
# ADD BASE RSC /l 0x409 /d "_DEBUG"
|
||||
# ADD RSC /l 0x409 /d "_DEBUG"
|
||||
BSC32=bscmake.exe
|
||||
# ADD BASE BSC32 /nologo
|
||||
# ADD BSC32 /nologo
|
||||
LIB32=link.exe -lib
|
||||
# ADD BASE LIB32 /nologo
|
||||
# ADD LIB32 /nologo
|
||||
|
||||
!ENDIF
|
||||
|
||||
# Begin Target
|
||||
|
||||
# Name "mt - Win32 Release"
|
||||
# Name "mt - Win32 Debug"
|
||||
# Begin Group "Source Files"
|
||||
|
||||
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CCondVar.cpp
|
||||
# End Source File
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CLock.cpp
|
||||
# End Source File
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CMutex.cpp
|
||||
# End Source File
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CThread.cpp
|
||||
# End Source File
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CThreadRep.cpp
|
||||
# End Source File
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CTimerThread.cpp
|
||||
# End Source File
|
||||
# End Group
|
||||
# Begin Group "Header Files"
|
||||
|
||||
# PROP Default_Filter "h;hpp;hxx;hm;inl"
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CCondVar.h
|
||||
# End Source File
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CLock.h
|
||||
# End Source File
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CMutex.h
|
||||
# End Source File
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CThread.h
|
||||
# End Source File
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CThreadRep.h
|
||||
# End Source File
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\CTimerThread.h
|
||||
# End Source File
|
||||
# Begin Source File
|
||||
|
||||
SOURCE=.\XThread.h
|
||||
# End Source File
|
||||
# End Group
|
||||
# End Target
|
||||
# End Project
|
||||
Reference in New Issue
Block a user