From 78dd12e2dd8b9661c4e749bb547e606aa530cf01 Mon Sep 17 00:00:00 2001 From: smogm Date: Sun, 11 Jan 2015 17:52:31 +0100 Subject: [PATCH] add mutex and thread abstraction --- generic-pc/mutex_abstraction.cpp | 22 +++++++++++++++++++++ generic-pc/mutex_abstraction.h | 20 +++++++++++++++++++ generic-pc/thread_abstraction.cpp | 33 +++++++++++++++++++++++++++++++ generic-pc/thread_abstraction.h | 25 +++++++++++++++++++++++ 4 files changed, 100 insertions(+) create mode 100644 generic-pc/mutex_abstraction.cpp create mode 100644 generic-pc/mutex_abstraction.h create mode 100644 generic-pc/thread_abstraction.cpp create mode 100644 generic-pc/thread_abstraction.h diff --git a/generic-pc/mutex_abstraction.cpp b/generic-pc/mutex_abstraction.cpp new file mode 100644 index 0000000..a5a886f --- /dev/null +++ b/generic-pc/mutex_abstraction.cpp @@ -0,0 +1,22 @@ +#include "mutex_abstraction.h" + +Mutex::Mutex() : + mMutex() +{ + pthread_mutex_init(&mMutex, 0); +} + +Mutex::~Mutex() +{ + pthread_mutex_destroy(&mMutex); +} + +void Mutex::lock() +{ + pthread_mutex_lock(&mMutex); +} + +void Mutex::unlock() +{ + pthread_mutex_unlock(&mMutex); +} diff --git a/generic-pc/mutex_abstraction.h b/generic-pc/mutex_abstraction.h new file mode 100644 index 0000000..c2b78d8 --- /dev/null +++ b/generic-pc/mutex_abstraction.h @@ -0,0 +1,20 @@ +#ifndef _MUTEX_ABSTRACTION_H +#define _MUTEX_ABSTRACTION_H + +#include + +class Mutex +{ + pthread_mutex_t mMutex; + + Mutex(const Mutex&); + const Mutex& operator=(const Mutex&); + + public: + Mutex(); + virtual ~Mutex(); + void lock(); + void unlock(); +}; + +#endif diff --git a/generic-pc/thread_abstraction.cpp b/generic-pc/thread_abstraction.cpp new file mode 100644 index 0000000..57b7759 --- /dev/null +++ b/generic-pc/thread_abstraction.cpp @@ -0,0 +1,33 @@ +#include "thread_abstraction.h" + +Thread::Thread() : + mIsRunning(false), + mThread() +{ +} + +Thread::~Thread() +{ + // if thread is still running on object destruction, cancel thread the hard way: + if (mIsRunning) + { + pthread_cancel(mThread); + } +} + +void Thread::startThread() +{ + mIsRunning = true; + pthread_create(&mThread, 0, &Thread::runThread, this); +} + +void Thread::joinThread() +{ + pthread_join(mThread, 0); + mIsRunning = false; +} + +void* Thread::runThread(void* ptr) +{ + ((Thread*)ptr)->run(); +} diff --git a/generic-pc/thread_abstraction.h b/generic-pc/thread_abstraction.h new file mode 100644 index 0000000..3c3e35f --- /dev/null +++ b/generic-pc/thread_abstraction.h @@ -0,0 +1,25 @@ +#ifndef _THREAD_ABSTRACTION_H +#define _THREAD_ABSTRACTION_H + +#include + +class Thread +{ + bool mIsRunning; + pthread_t mThread; + + static void* runThread(void*); + Thread(const Thread&); + const Thread& operator=(const Thread&); + + public: + Thread(); + ~Thread(); + void startThread(); + void joinThread(); + + protected: + virtual void run() = 0; +}; + +#endif