summaryrefslogtreecommitdiff
path: root/tvapi/libtv/tvutils/CThread.h (plain)
blob: a660cc89d6ea8926a609850445b7bd2986b88069
1/*
2reference android api, just linux pthread
3*/
4
5#ifndef _TV_UTILS_THREAD_H
6#define _TV_UTILS_THREAD_H
7
8#include <stdint.h>
9#include <sys/types.h>
10#include <time.h>
11#include <pthread.h>
12#include "CCondition.h"
13#include "CMutex.h"
14
15class CThread {
16public:
17 CThread();
18 virtual ~CThread();
19
20 // Start the thread in threadLoop() which needs to be implemented.
21 virtual int run(const char *name = 0,
22 int priority = 0,
23 int stack = 0);
24 //request thread object to exit, asynchronous to exit.
25 virtual void requestExit();
26
27 // Good place to do one-time initializations
28 virtual int readyToRun();
29
30 // Call requestExit() and wait until this object's thread exits.
31 // BE VERY CAREFUL of deadlocks. In particular, it would be silly to call
32 // this function from this object's thread. Will return WOULD_BLOCK in
33 // that case.
34 int requestExitAndWait();
35
36 // Wait until this object's thread exits. Returns immediately if not yet running.
37 // Do not call from this object's thread; will return WOULD_BLOCK in that case.
38 int join();
39protected:
40 // exitPending() returns true if requestExit() has been called.
41 bool exitPending() const;
42
43private:
44 // Derived class must implement threadLoop(). The thread starts its life
45 // here. There are two ways of using the Thread object:
46 // 1) loop: if threadLoop() returns true, it will be called again if
47 // requestExit() wasn't called.
48 // 2) once: if threadLoop() returns false, the thread will exit upon return.
49 virtual bool threadLoop() = 0;
50
51private:
52 static void *_threadLoop(void *user);
53 pthread_t mThreadId;
54 mutable CMutex mLock;
55 CCondition mThreadExitedCondition;
56 int mStatus;
57 //note that all accesses of mExitPending and mRunning need to hold mLock
58 volatile bool mExitPending;
59 volatile bool mRunning;
60};
61#endif
62