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