/** * @file task.h * @author myusgun@gmail.com * @brief task */ #ifndef __task_h__ #define __task_h__ #include "cf/exception.h" #define SYNCHRONIZED(_s) for (cf::task::scopedLock _sl(&_s) ; _sl.synchronizer()->locked() ; _sl.synchronizer()->unlock()) namespace cf { /** * task */ namespace task { /** * interface of synchronizer, like a mutex */ class ISynchronizer { public: /** * lock * @throw cf::exception */ virtual cf::void_t lock() throw (cf::exception) = 0; /** * unlock * @throw cf::exception */ virtual cf::void_t unlock() throw (cf::exception) = 0; /** * is locked ? * @return true; false */ virtual cf::bool_t locked() const = 0; }; /** * mutex */ class mutex : public ISynchronizer { private: cf::bool_t mIsLocked; cf::void_t * mMutex; public: /** * constructor * @throw cf::exception */ mutex() throw (cf::exception); /** * destructor */ ~mutex(); /** * lock * @throw cf::exception */ cf::void_t lock() throw (cf::exception); /** * unlock * @throw cf::exception */ cf::void_t unlock() throw (cf::exception); /** * trylock * @return true; false */ cf::bool_t trylock() throw (cf::exception); /** * is locked ? * @return true; false */ cf::bool_t locked() const; }; /** * scoped lock * @see SYNCHRONIZE */ class scopedLock { private: ISynchronizer * mSynchronizer; public: /** * constructor for locking * @throw cf::exception */ scopedLock(ISynchronizer * inst) throw (cf::exception); /** * destructor for unlocking */ ~scopedLock(); /** * get synchronizer * @return an instance of synchronizer */ ISynchronizer * synchronizer(); }; /** * thread */ class thread { public: /** a prototype of worker function */ typedef cf::int32_t(*ThreadFunction)(cf::void_t *); typedef struct _THREAD_CTX { cf::bool_t mIsRunning; ThreadFunction mCallback; cf::void_t * mArgument; cf::int32_t mReturned; } THREAD_CTX; private: THREAD_CTX mCtx; cf::void_t * mThreadID; mutex mMutex; public: /** * constructor * @param callback thread worker function */ thread(const ThreadFunction callback) throw (cf::exception); /** * destructor */ ~thread(); /** * start thread * @param arg thread argument * @throw cf::exception */ cf::void_t start(cf::void_t * arg) throw (cf::exception); /** * join thread */ cf::void_t join(); /** * is running ? * @return true; false */ cf::bool_t isRunning() const; /** * get thread id * @return thread id */ static cf::uint32_t id(); /** * sleep * @param milliseconds milliseconds */ static cf::void_t sleep(const cf::int32_t milliseconds); }; /** * process */ class process { public: /** * get process id * @return process id */ static cf::uint32_t id(); }; } } #endif // #ifndef __task_h__