summaryrefslogtreecommitdiff
path: root/lib/thread.h
blob: fcaaf4be015be32bcf870622b12fe92e46a757c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
 * thread.h
 *
 * See the README file for copyright information and how to reach the author.
 *
 */

#ifndef __LIB_THREAD_H
#define __LIB_THREAD_H

#include "common.h"

class cCondWait 
{
   public:

      cCondWait();
      ~cCondWait();

      bool Wait(int TimeoutMs = 0);
      void Signal();

      static void SleepMs(int TimeoutMs);

   private:

      pthread_mutex_t mutex;
      pthread_cond_t cond;
      bool signaled;
};

class cCondVar 
{
   public:

      cCondVar();
      ~cCondVar();

      void Wait(cMyMutex &Mutex);
      bool TimedWait(cMyMutex &Mutex, int TimeoutMs);
      void Broadcast();

   private:

      pthread_cond_t cond;
};

//***************************************************************************
// Class cThread 
//***************************************************************************

class cThread 
{
   public:

      cThread(const char *Description = NULL, bool LowPriority = false);
      virtual ~cThread();

      void SetDescription(const char* Description, ...) __attribute__ ((format (printf, 2, 3)));
      bool Start(int s = no, int stackSize = na);
      bool Active();
      void SetPriority(int priority);
      void SetIOPriority(int priority);
      void Cancel(int WaitSeconds = 0);

      static pid_t ThreadId();

   private:

      static void* StartThread(cThread *Thread);

      pthread_t childTid;
      pid_t childThreadId;
      char* description;
      bool lowPriority;
      int silent;
      pthread_attr_t attr;
   
   protected:

      virtual void action() = 0;

      void Lock()          { mutex.Lock(); }
      void Unlock()        { mutex.Unlock(); }
      bool Running()       { return running; }

      cCondVar waitCondition;
      cMyMutex mutex;
      bool active;
      bool running;
};

//***************************************************************************

#endif // __LIB_THREAD_H