fastdo  0.6.16
threads.hpp
浏览该文件的文档.
1 #ifndef __THREADS_HPP__
2 #define __THREADS_HPP__
3 //
4 // threads 提供线程相关的功能
5 //
6 
7 namespace winux
8 {
9 // 类型定义
10 #if defined(OS_WIN)
11 typedef DWORD pid_t;
12 #else
13 typedef int pid_t;
14 #endif
15 
16 //=========================================================================================
20 class ThreadSysError : public Error
21 {
22 public:
23  ThreadSysError( int errCode, AnsiString const & errStr ) throw() : Error( errCode, errStr ) { }
25  int getErrCode() const throw() { return this->getErrType(); }
26 };
27 
28 //=========================================================================================
29 // 线程相关错误返回值为errno.h定义的错误码
30 //=========================================================================================
31 
34 {
35  schedOther = 0,
40 };
41 
44 {
46 };
47 
50 {
51 #ifdef Yield
52 #undef Yield
53 #endif
54  static int Yield(void);
55  static int GetPriorityMin( SchedulePolicy policy );
56  static int GetPriorityMax( SchedulePolicy policy );
58  static void SetScheduler( pid_t pid, SchedulePolicy policy );
60  static SchedulePolicy GetScheduler( pid_t pid );
61 };
62 
65 {
66 public:
68  explicit ThreadAttr( bool isCreate = true );
69  ~ThreadAttr();
70 
71  ThreadAttr( ThreadAttr && other );
72  ThreadAttr & operator = ( ThreadAttr && other );
73 
75  int create();
76 
78  int destroy();
79 
81  operator bool() const;
82 
83 public:
84  //attributes:
85 
88  {
89  threadCreateJoinable = 0,
90  threadCreateDetached = 1,
91  };
93  void setDetachState( DetachStateType detachState = threadCreateJoinable );
95  DetachStateType getDetachState() const;
96 
98  void setStackSize( size_t stackSize );
100  size_t getStackSize() const;
101 
105  void setSchedParam( ScheduleParam const & param );
109  ScheduleParam getSchedParam() const;
110 
114  void setSchedPolicy( SchedulePolicy policy );
118  SchedulePolicy getSchedPolicy() const;
119 
120 private:
122  friend class Thread;
123 
125 };
126 
129 {
130 public:
131  ThreadId();
132  ~ThreadId();
133  ThreadId( ThreadId const & other );
134  ThreadId & operator = ( ThreadId const & other );
135  ThreadId( ThreadId && other );
136  ThreadId & operator = ( ThreadId && other );
137 
138  bool operator == ( ThreadId const & other ) const;
139  bool operator != ( ThreadId const & other ) const { return !this->operator == (other); }
140 
141 private:
143 
144  friend class Thread;
145 };
146 
147 class ThreadGroup;
150 {
151 public:
153  typedef void * (* ThreadFuncPtr)( void * param );
154 
155 public:
157  static ThreadId Self();
158 
160  static void Exit( void * exitVal = NULL );
161 
165  static void * Join( Thread & otherThread );
166 
167  // attributes
171  static void SetConcurrency( int newLevel );
173  static int GetConcurrency( void );
174 
175 private:
176  // 默认线程处理函数, param被传入Thread对象, 调用thObj->run()
177  static void * _ThreadDefaultFunc( void * param );
178 
179 public:
185  explicit Thread( bool isStartup = false ) : _param(nullptr), _attr(false), _exitVal(nullptr), _deleter(nullptr), _group(nullptr), _isRunning(false)
186  {
187  if ( isStartup ) this->startup();
188  }
189 
193  template < typename _Fx, typename... _ArgType >
194  explicit Thread( bool isStartup, _Fx routine, _ArgType&&... arg ) : _param(nullptr), _attr(false), _exitVal(nullptr), _deleter(nullptr), _group(nullptr), _isRunning(false)
195  {
196  this->setRunable( routine, std::forward<_ArgType>(arg)... );
197  if ( isStartup ) this->startup();
198  }
199 
201  virtual ~Thread();
202 
204  Thread( Thread && other );
205 
207  Thread & operator = ( Thread && other );
208 
213  int startup();
214 
216  template < typename _Fx, typename... _ArgType >
217  int startup( _Fx routine, _ArgType&&... arg )
218  {
219  this->setRunable( routine, std::forward<_ArgType>(arg)... );
220  return this->startup();
221  }
222 
224  int startupEx( ThreadFuncPtr startRoutine, void * param );
225 
227  void * joined();
228 
235  int detach();
236 
237 public:
238  //attributes:
239 
243  void setSchedParam( SchedulePolicy policy, int priority );
247  void getSchedParam( SchedulePolicy * policy, int * priority ) const;
248 
250  ThreadAttr & attr();
251 
253  template < typename _Fx, typename... _ArgType >
254  Thread & setRunable( _Fx routine, _ArgType&&... arg )
255  {
256  this->_runable.attachNew( NewRunable( routine, std::forward<_ArgType>(arg)... ) );
257  return *this;
258  }
259 
261  Thread & setDeleter( SimpleDeleterContext * deleter = NULL )
262  {
263  _deleter = deleter;
264  return *this;
265  }
266 
268  Thread & setDefaultDeleter() { return this->setDeleter( new SimpleDefaultDeleterContext<Thread*>(this) ); }
269 
271  template < typename _Dt >
272  Thread & setCustomDeleter( _Dt fn ) { return this->setDeleter( new SimpleCustomDeleterContext< Thread*, _Dt >( this, fn ) ); }
273 
275  void * getExitVal() const { return _exitVal; }
277  Thread & setExitVal( void * exitVal )
278  {
279  _exitVal = exitVal;
280  return *this;
281  }
282 
284  ThreadId get() const
285  {
286  return _threadId;
287  }
288 
289 protected:
291  virtual void run();
292  struct _ThreadFuncParam * _param;
293 
294 private:
295  ThreadAttr _attr;
296  void * _exitVal;
297  SimpleDeleterContext * _deleter;
298  ThreadGroup * _group;
299  bool _isRunning;
300  ThreadId _threadId;
301  SimplePointer<Runable> _runable;
302 
303  friend class ThreadGroup;
304 
306 };
307 
308 //=========================================================================================
311 {
312 public:
313  explicit MutexAttr( bool isCreate = true );
314  ~MutexAttr();
315 
316  MutexAttr( MutexAttr && other );
317  MutexAttr & operator = ( MutexAttr && other );
318 
320  int create();
321 
323  int destroy();
324 
326  operator bool() const;
327 
328 public:
331  {
335  mtxDefault
336  };
337  int setType( MutexType type );
338 
339  MutexType getType() const;
340 
341 private:
343  friend class Mutex;
344 
346 };
347 
350 {
351 public:
352  explicit Mutex( bool isCreate = false );
353  ~Mutex();
354 
355  Mutex( Mutex && other );
356  Mutex & operator = ( Mutex && other );
357 
359  virtual int create();
360 
362  int destroy();
363 
364  bool lock();
365  bool tryLock();
366  bool unlock();
367 
369  MutexAttr & attr();
370 private:
371  MutexAttr _attr;
373  friend class Condition;
374 
376 };
377 
380 {
381 public:
382  explicit RecursiveMutex( bool isCreate = false );
383  int create() override;
384 };
385 
386 //=========================================================================================
389 {
390 public:
391  explicit ConditionAttr( bool isCreate = true );
392  ~ConditionAttr();
393 
394  ConditionAttr( ConditionAttr && other );
395  ConditionAttr & operator = ( ConditionAttr && other );
396 
398  int create();
399 
401  int destroy();
402 
404  operator bool() const;
405 
406 private:
408  friend class Condition;
409 
411 };
412 
415 {
416 public:
417  explicit Condition( bool isCreate = false );
418  ~Condition();
419 
420  Condition( Condition && other );
421  Condition & operator = ( Condition && other );
422 
424  int create();
425 
427  int destroy();
428 
433  bool wait( Mutex & mutex, double sec = -1 );
434 
439  template < typename _Predicate >
440  bool waitUntil( _Predicate pred, Mutex & mutex, double sec = -1 )
441  {
442  while ( !pred() )
443  if ( !this->wait( mutex, sec ) )
444  return pred();
445  return true;
446  }
447 
449  int notify();
450 
452  int notifyAll();
453 
454  ConditionAttr & attr();
455 
456 private:
457  ConditionAttr _attr;
460 };
461 
462 //===========================================================================================
465 {
466 public:
467  explicit TlsKey( void (*destructor)( void *pv ) = NULL );
468  ~TlsKey();
469 
470  TlsKey( TlsKey && other );
471  TlsKey & operator = ( TlsKey && other );
472 
474  int create( void (*destructor)( void *pv ) = NULL );
475 
477  int destroy();
478 
480  void * get() const;
481 
482 private:
484 
485  friend class TlsVar;
487 };
488 
491 {
492 public:
493  explicit TlsVar( TlsKey & tlsKey );
494  ~TlsVar();
495 
496  TlsVar( TlsVar && other );
497  TlsVar & operator = ( TlsVar && other );
498 
499  void * get();
500  void * get() const;
501  void set( void * v );
502 
503  template < typename _Ty >
504  _Ty get() { return reinterpret_cast<_Ty>( this->get() ); }
505  template < typename _Ty >
506  _Ty get() const { return reinterpret_cast<_Ty>( this->get() ); }
507 
508  template < typename _Ty >
509  void set( _Ty v ) { this->set( reinterpret_cast<void*>(v) ); }
510 
511  template < typename _Ty >
512  _Ty & ref() { return *reinterpret_cast<_Ty*>( this->get() ); }
513  template < typename _Ty >
514  _Ty const & ref() const { return *reinterpret_cast<_Ty*>( this->get() ); }
515 
516 private:
517  TlsKey * _tlsKey;
519 };
520 
521 //===========================================================================================
522 
527 {
528 public:
529 
531  ThreadGroup() : _mtxGroup(true), _cdtGroup(true)
532  {
533  }
534 
536  template < typename _Fx, typename... _ArgType >
537  ThreadGroup( size_t count, _Fx fn, _ArgType&&... arg ) : _mtxGroup(true), _cdtGroup(true)
538  {
539  for ( size_t i = 0; i < count; i++ )
540  {
541  Thread * p = new Thread( false, fn, std::forward<_ArgType>(arg)... );
542  p->_group = this;
543  _threads.emplace_back(p);
544  }
545  }
546 
547  virtual ~ThreadGroup()
548  {
549  }
550 
551  ThreadGroup( ThreadGroup && other ) : _mtxGroup( std::move(other._mtxGroup) ), _cdtGroup( std::move(other._cdtGroup) ), _threads( std::move(other._threads) )
552  {
553  }
554 
555  ThreadGroup & operator = ( ThreadGroup && other )
556  {
557  if ( this != &other )
558  {
559  // 先释放自身
560  this->wait();
561 
562  _mtxGroup = std::move(other._mtxGroup);
563  _cdtGroup = std::move(other._cdtGroup);
564  _threads = std::move(other._threads);
565  }
566  return *this;
567  }
568 
570  ThreadGroup & destroy();
571 
573  template < typename _Fx, typename... _ArgType >
574  ThreadGroup & create( size_t count, _Fx fn, _ArgType&&... arg )
575  {
576  this->destroy();
577 
578  for ( size_t i = 0; i < count; i++ )
579  {
580  Thread * p = new Thread( false, fn, std::forward<_ArgType>(arg)... );
581  p->_group = this;
582  _threads.emplace_back(p);
583  }
584  return *this;
585  }
586 
588  template < class _ThreadCls >
589  ThreadGroup & create( size_t count )
590  {
591  this->destroy();
592 
593  for ( size_t i = 0; i < count; i++ )
594  {
595  Thread * p = new _ThreadCls();
596  p->_group = this;
597  _threads.emplace_back(p);
598  }
599  return *this;
600  }
601 
603  ThreadGroup & startup();
604 
608  bool wait( double sec = -1 );
609 
610 private:
611  static void * _ThreadGroupDefaultFunc( void * param );
612 
613  Mutex _mtxGroup; // 互斥量保护数据
614  Condition _cdtGroup; // 用于判断组中线程是否全部运行完毕
615  std::vector< SimplePointer<Thread> > _threads;
616 
618 };
619 
620 
621 } // namespace winux
622 
623 #endif // __THREADS_HPP__
XString< char > AnsiString
Definition: utilities.hpp:257
Thread(bool isStartup, _Fx routine, _ArgType &&...arg)
构造函数2
Definition: threads.hpp:194
RunableT< _Fx, std::tuple< typename std::decay< _ArgType >::type... > > * NewRunable(_Fx fn, _ArgType &&...arg)
创建一个Runable对象
Definition: utilities.hpp:119
ThreadGroup(ThreadGroup &&other)
Definition: threads.hpp:551
同步锁对象接口
Definition: system.hpp:207
线程调度相关静态方法
Definition: threads.hpp:49
Simple默认删除器场景
Definition: smartptr.hpp:54
它是一种实时的先进先出调用策略,且只能在超级用户下运行。这种调用策略仅仅被使用于优先级大于0的线程。它...
Definition: threads.hpp:36
#define WINUX_DLL
Definition: utilities.hpp:60
void * getExitVal() const
取得退出值
Definition: threads.hpp:275
Simple自定义删除器场景
Definition: smartptr.hpp:69
MutexType
互斥锁类型
Definition: threads.hpp:330
int pid_t
Definition: threads.hpp:13
Thread & setCustomDeleter(_Dt fn)
设置自定义删除器场景以便默认线程函数删除Thread对象自己
Definition: threads.hpp:272
Thread & setDefaultDeleter()
设置默认删除器场景以便默认线程函数删除Thread对象自己
Definition: threads.hpp:268
STL namespace.
Thread(bool isStartup=false)
构造函数1
Definition: threads.hpp:185
调度参数
Definition: threads.hpp:43
条件变量
Definition: threads.hpp:414
ThreadGroup(size_t count, _Fx fn, _ArgType &&...arg)
构造函数2 提供一个线程处理例程,并指定创建的线程数量
Definition: threads.hpp:537
_Ty & ref()
Definition: threads.hpp:512
Simple删除器场景基类
Definition: smartptr.hpp:28
#define DISABLE_OBJECT_COPY(clsname)
Definition: utilities.hpp:85
virtual ~ThreadGroup()
Definition: threads.hpp:547
它是默认的线程分时调度策略,所有的线程的优先级别都是0,线程的调度是通过分时来完成的。如果系统使用这种...
Definition: threads.hpp:35
互斥量
Definition: threads.hpp:349
互斥量属性
Definition: threads.hpp:310
条件变量属性
Definition: threads.hpp:388
SchedulePolicy
线程调度策略
Definition: threads.hpp:33
线程组
Definition: threads.hpp:526
普通互斥锁
Definition: threads.hpp:332
bool waitUntil(_Predicate pred, Mutex &mutex, double sec=-1)
等待谓词条件达成
Definition: threads.hpp:440
ThreadSysError(int errCode, AnsiString const &errStr)
Definition: threads.hpp:23
ThreadGroup()
构造函数1 默认
Definition: threads.hpp:531
TLS Var.
Definition: threads.hpp:490
线程
Definition: threads.hpp:149
Thread & setRunable(_Fx routine, _ArgType &&...arg)
设置Runable,run()默认会调用它
Definition: threads.hpp:254
线程相关错误
Definition: threads.hpp:20
struct _ThreadFuncParam * _param
线程函数的参数
Definition: threads.hpp:292
线程ID
Definition: threads.hpp:128
int getErrCode() const
获取错误代码
Definition: threads.hpp:25
Thread & setExitVal(void *exitVal)
设置退出值,可在run()中调用
Definition: threads.hpp:277
ThreadGroup & create(size_t count)
创建一定数量指定的派生类线程
Definition: threads.hpp:589
virtual int getErrType() const
Definition: utilities.hpp:849
简单指针
Definition: smartptr.hpp:302
错误类
Definition: utilities.hpp:838
TLS Key.
Definition: threads.hpp:464
Thread & setDeleter(SimpleDeleterContext *deleter=NULL)
设置删除器场景以便默认线程函数删除Thread对象自己
Definition: threads.hpp:261
DetachStateType
分离状态类型
Definition: threads.hpp:87
ThreadGroup & create(size_t count, _Fx fn, _ArgType &&...arg)
按指定的线程处理例程,创建一定数量的线程
Definition: threads.hpp:574
_Ty const & ref() const
Definition: threads.hpp:514
线程属性
Definition: threads.hpp:64
鉴于SCHED_FIFO调度策略的一些缺点,SCHED_RR对SCHED_FIFO做出了一些增强功能。从实质上看,它还是SCHED_FIF...
Definition: threads.hpp:37
跨平台基础功能库
Definition: archives.hpp:7
int startup(_Fx routine, _ArgType &&...arg)
实际创建一个线程,提供你自己的处理例程
Definition: threads.hpp:217