1 /* Later delete this file and use Parallel Patterns Library instead */
6 template <class ResultType>
12 std::function<ResultType()> m_func;
19 explicit Task(TaskParams *pParams) : m_pParams(pParams)
24 Task() : m_pParams(nullptr) {}
27 m_pParams = other.m_pParams;
28 other.m_pParams = nullptr;
31 Task& operator=(Task&& other)
33 m_pParams = other.m_pParams;
34 other.m_pParams = nullptr;
40 EnterCriticalSection(&g_cs);
43 if (m_pParams->m_completed)
45 CloseHandle(m_pParams->m_hThread);
50 m_pParams->m_detached = true;
53 LeaveCriticalSection(&g_cs);
57 static unsigned __stdcall ThreadProc(void *pParam)
59 TaskParams *pParams = reinterpret_cast<TaskParams *>(pParam);
60 pParams->m_result = pParams->m_func();
61 EnterCriticalSection(&g_cs);
62 if (pParams->m_detached)
64 CloseHandle(pParams->m_hThread);
69 pParams->m_completed = true;
71 LeaveCriticalSection(&g_cs);
76 template <typename FuncType>
77 static auto Create(FuncType func)
80 TaskParams *pParams = new TaskParams();
81 pParams->m_detached = false;
82 pParams->m_completed = false;
83 pParams->m_func = func;
84 pParams->m_hThread = reinterpret_cast<HANDLE>(_beginthreadex(nullptr, 0, ThreadProc, pParams, 0, &threadId));
85 return Task<decltype(func())>(pParams);
90 WaitForSingleObject(m_pParams->m_hThread, INFINITE);
91 return m_pParams->m_result;
95 TaskParams *m_pParams;
98 template <typename FuncType>
99 auto CreateTask(FuncType func)
101 return Task<decltype(func())>::Create(func);
104 extern CRITICAL_SECTION g_cs;
105 extern bool g_initialized;