From a7c4cbe53aad51b3e74fa9cb1af975cb8d356954 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Mon, 5 Aug 2013 16:06:16 -0400 Subject: CLI debugging, got rid of nasty old Thread class and replaced with newer cleaner portable idiom. --- node/Thread.hpp | 104 +++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 73 insertions(+), 31 deletions(-) (limited to 'node/Thread.hpp') diff --git a/node/Thread.hpp b/node/Thread.hpp index 9b399a00..444da2be 100644 --- a/node/Thread.hpp +++ b/node/Thread.hpp @@ -28,62 +28,104 @@ #ifndef _ZT_THREAD_HPP #define _ZT_THREAD_HPP -#include "NonCopyable.hpp" +#include + +#include "Constants.hpp" #include "AtomicCounter.hpp" +#ifdef __WINDOWS__ + +todo need windows; + +#else + +#include +#include +#include +#include +#include + namespace ZeroTier { +template +static void *___zt_threadMain(void *instance) +{ + try { + ((C *)instance)->threadMain(); + } catch ( ... ) {} + return (void *)0; +} + /** - * Wrapper for OS-dependent thread functions like pthread_create, etc. + * A thread of a given class type + * + * @tparam C Class using Thread */ -class Thread : NonCopyable +template +class Thread { public: - Thread(); - virtual ~Thread(); + Thread() + throw() + { + memset(&_tid,0,sizeof(_tid)); + } - /** - * Start thread -- can only be called once - */ - void start(); + Thread(const Thread &t) + throw() + { + memcpy(&_tid,&(t._tid),sizeof(_tid)); + } - /** - * Wait for thread to terminate - * - * More than one thread should not simultaneously use join(). - */ - void join(); + inline Thread &operator=(const Thread &t) + throw() + { + memcpy(&_tid,&(t._tid),sizeof(_tid)); + return *this; + } /** - * @return True if thread is running + * Start a new thread + * + * @param instance Instance whose threadMain() method gets called by new thread + * @return Thread identifier + * @throws std::runtime_error Unable to create thread */ - inline bool running() const { return (*_running > 0); } + static inline Thread start(C *instance) + throw(std::runtime_error) + { + Thread t; + if (pthread_create(&t._tid,(const pthread_attr_t *)0,&___zt_threadMain,instance)) + throw std::runtime_error("pthread_create() failed, unable to create thread"); + return t; + } /** - * Internal bounce method; do not call or override + * Join to a thread, waiting for it to terminate + * + * @param t Thread to join */ - void __intl_run(); + static inline void join(const Thread &t) + { + pthread_join(t._tid,(void **)0); + } /** * Sleep the current thread * - * @param ms Milliseconds to sleep + * @param ms Number of milliseconds to sleep */ - static void sleep(unsigned long ms); - -protected: - /** - * Override to set a thread main function - */ - virtual void main() - throw(); + static inline void sleep(unsigned long ms) + { + usleep(ms * 1000); + } private: - void *_impl; - AtomicCounter _running; - volatile bool _notInit; + pthread_t _tid; }; } // namespace ZeroTier +#endif // __WINDOWS__ / !__WINDOWS__ + #endif -- cgit v1.2.3