Created
December 22, 2011 10:52
-
-
Save StonedXander/1509901 to your computer and use it in GitHub Desktop.
Simple Thread class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* thread.h | |
* by Stoned Xander (2011) | |
*/ | |
#ifndef THREAD_H_ | |
#define THREAD_H_ | |
#ifdef WITH_PTHREAD | |
#include <pthread.h> | |
#endif | |
template<typename D> class Thread { | |
public: | |
/** | |
* Constructor. | |
* Get the delegate into account. | |
*/ | |
Thread(D *d) : | |
delegate(d), thread(-1), valid(false) { | |
} | |
/** | |
* Run the thread. | |
* @return <code>true</code> if the thread has been successfully launched. | |
*/ | |
bool run() { | |
if (!valid) { | |
// Create it. | |
#ifdef WITH_PTHREAD | |
valid = pthread_create(&thread, NULL, &Thread::adapt, delegate) == 0; | |
#endif | |
} | |
return valid; | |
} | |
/** | |
* Wait for the thread to finish. | |
*/ | |
void join() { | |
if (valid) { | |
#ifdef WITH_PTHREAD | |
pthread_join(thread, NULL); | |
valid = false; | |
#endif | |
} | |
} | |
private: | |
/** | |
* Bridge static method. | |
*/ | |
static void *adapt(void *data) { | |
D *d = (D *) data | |
return d->run(); | |
} | |
/** | |
* Delegate object. | |
*/ | |
D *delegate; | |
#ifdef WITH_PTHREAD | |
pthread_t thread; | |
#endif | |
bool valid; | |
}; | |
#endif /* THREAD_H_ */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment