Newton Dynamics  4.00
ndThreadBackgroundWorker.h
1 /* Copyright (c) <2003-2022> <Julio Jerez, Newton Game Dynamics>
2 *
3 * This software is provided 'as-is', without any express or implied
4 * warranty. In no event will the authors be held liable for any damages
5 * arising from the use of this software.
6 *
7 * Permission is granted to anyone to use this software for any purpose,
8 * including commercial applications, and to alter it and redistribute it
9 * freely, subject to the following restrictions:
10 *
11 * 1. The origin of this software must not be misrepresented; you must not
12 * claim that you wrote the original software. If you use this software
13 * in a product, an acknowledgment in the product documentation would be
14 * appreciated but is not required.
15 *
16 * 2. Altered source versions must be plainly marked as such, and must not be
17 * misrepresented as being the original software.
18 *
19 * 3. This notice may not be removed or altered from any source distribution.
20 */
21 
22 #ifndef __ND_THREAD_BACKGROUNG_WORKER_H_
23 #define __ND_THREAD_BACKGROUNG_WORKER_H_
24 
25 #include "ndCoreStdafx.h"
26 #include "ndTypes.h"
27 #include "ndList.h"
28 #include "ndSemaphore.h"
29 #include "ndClassAlloc.h"
30 #include "ndThreadPool.h"
31 
33 
35 {
36  public:
37  enum ndTaskState
38  {
39  m_taskInProccess,
40  m_taskCompleted,
41  };
42 
44  :m_taskState(m_taskCompleted)
45  {
46  }
47 
48  virtual ~ndBackgroundTask() {}
49 
50  ndTaskState taskState() const
51  {
52  return m_taskState.load();
53  }
54 
55  D_CORE_API void Sync() const;
56 
57  protected:
58  virtual void Execute(ndThreadPool* const threadPool) = 0;
59 
60  private:
61  ndAtomic<ndTaskState> m_taskState;
62  friend class ndThreadBackgroundWorker;
63 };
64 
65 class ndThreadBackgroundWorker: public ndThreadPool, public ndList<ndBackgroundTask*, ndContainersFreeListAlloc<ndBackgroundTask*>>
66 {
67  public:
68  D_CORE_API ndThreadBackgroundWorker();
69  D_CORE_API ~ndThreadBackgroundWorker();
70 
71  D_CORE_API void Terminate();
72  D_CORE_API void SendTask(ndBackgroundTask* const job);
73 
74  private:
75  virtual void ThreadFunction();
76 
77  ndSpinLock m_lock;
78  ndAtomic<bool> m_inLoop;
79  ndAtomic<bool> m_teminate;
80  ndSemaphore m_queueSemaphore;
81 };
82 
83 #endif
ndSpinLock
Simple spin lock for synchronizing threads for very short period of time.
Definition: ndUtils.h:212
ndThreadBackgroundWorker
Definition: ndThreadBackgroundWorker.h:66
ndList
Definition: ndList.h:33
ndBackgroundTask
Definition: ndThreadBackgroundWorker.h:35
ndSemaphore
Generic counting semaphore for thread synchronization.
Definition: ndSemaphore.h:29
ndThreadPool
Definition: ndThreadPool.h:65
ndAtomic< ndTaskState >