2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>
\r
4 * This file is part of CasparCG.
\r
6 * CasparCG is free software: you can redistribute it and/or modify
\r
7 * it under the terms of the GNU General Public License as published by
\r
8 * the Free Software Foundation, either version 3 of the License, or
\r
9 * (at your option) any later version.
\r
11 * CasparCG is distributed in the hope that it will be useful,
\r
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
14 * GNU General Public License for more details.
\r
16 * You should have received a copy of the GNU General Public License
\r
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
\r
21 #include "../StdAfx.h"
\r
24 #include <common/exception/win32_exception.h>
\r
28 Event::Event(bool bManualReset, bool bInitialState) : handle_(0)
\r
30 handle_ = CreateEvent(0, bManualReset, bInitialState, 0);
\r
32 throw std::exception("Failed to create event");
\r
39 //BOOL res = SetEvent(handle_);
\r
40 //if(res == FALSE) {
\r
41 // DWORD error = GetLastError();
\r
44 void Event::Reset() {
\r
45 ResetEvent(handle_);
\r
50 CloseHandle(handle_);
\r
53 bool Thread::static_bInstallWin32ExceptionHandler_ = true;
\r
55 Thread::Thread() : pRunnable_(0), hThread_(0), stopEvent_(TRUE, FALSE), timeout_(10000) {
\r
62 bool Thread::IsRunning() {
\r
64 if(WaitForSingleObject(hThread_, 0) == WAIT_OBJECT_0) {
\r
65 CloseHandle(hThread_);
\r
71 return (hThread_ != 0);
\r
74 bool Thread::Start(IRunnable* pRunnable) {
\r
76 if(pRunnable != 0) {
\r
77 pRunnable_ = pRunnable;
\r
79 hThread_ = CreateThread(0, 0, ThreadEntrypoint, this, 0, 0);
\r
84 return (hThread_ != 0);
\r
90 bool Thread::Stop(bool bWait) {
\r
91 bool returnValue = true;
\r
97 DWORD successCode = WaitForSingleObject(hThread_, timeout_);
\r
98 if(successCode != WAIT_OBJECT_0)
\r
99 returnValue = false;
\r
101 CloseHandle(hThread_);
\r
107 return returnValue;
\r
110 void Thread::EnableWin32ExceptionHandler(bool bEnable) {
\r
111 static_bInstallWin32ExceptionHandler_ = bEnable;
\r
114 DWORD WINAPI Thread::ThreadEntrypoint(LPVOID pParam) {
\r
115 Thread* pThis = reinterpret_cast<Thread*>(pParam);
\r
117 if(Thread::static_bInstallWin32ExceptionHandler_)
\r
118 win32_exception::install_handler();
\r
120 _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
\r
127 void Thread::Run() {
\r
128 bool bDoRestart = false;
\r
132 bDoRestart = false;
\r
133 stopEvent_.Reset();
\r
134 pRunnable_->Run(stopEvent_);
\r
136 catch(const std::exception& e) {
\r
137 bDoRestart = pRunnable_->OnUnhandledException(e);
\r
139 }while(bDoRestart);
\r