Skip to content

Instantly share code, notes, and snippets.

@TheBurnDoc
Created October 20, 2013 13:00
Show Gist options
  • Save TheBurnDoc/7069290 to your computer and use it in GitHub Desktop.
Save TheBurnDoc/7069290 to your computer and use it in GitHub Desktop.
Minimal pthread wrapper classes, including the thread class itself and the mutex and lock_guard counterparts. Inherit from this class and override the thread_main pure virtual function to define the thread's entry point.
#include <cstring>
#include <sched.h>
#include <pthread.h>
#include "thread.h"
thread::thread() : _running(false)
{
}
thread::~thread()
{
if (is_running())
{
detach();
join();
}
}
void thread::pthread_fn()
{
if (!is_running())
{
_running = true;
thread_main();
_running = false;
}
}
void thread::start()
{
if (!is_running())
pthread_create(&_handle, nullptr, &thread::pthread_fn, static_cast<void*>(this));
}
void thread::join()
{
if (is_running())
pthread_join(_handle, nullptr);
}
void thread::detach()
{
if (is_running())
pthread_detach(_handle);
}
void thread::yield()
{
if (is_running())
sched_yield();
}
mutex::mutex()
{
pthread_mutex_init(&_handle, nullptr);
}
void mutex::lock()
{
pthread_mutex_lock(&_handle);
}
void mutex::unlock()
{
pthread_mutex_unlock(&_handle);
}
lock_guard::lock_guard(mutex& mutex) : _mutex(mutex)
{
_mutex.lock();
}
lock_guard::~lock_guard()
{
_mutex.unlock();
}
#pragma once
class thread
{
public:
thread();
virtual ~thread();
void operator()() { start(); }
void start();
void join();
void detach();
void yield();
bool is_running() const { return _running; }
protected:
virtual void thread_main() = 0;
private:
void pthread_fn();
static void* pthread_fn(void* t)
{
static_cast<thread*>(t)->pthread_fn();
return nullptr;
}
pthread_t _handle;
bool _running;
};
class mutex
{
public:
mutex();
void lock();
void unlock();
private:
pthread_mutex_t _handle;
};
class lock_guard
{
public:
explicit lock_guard( mutex& mutex );
~lock_guard();
private:
mutex _mutex;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment