2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
\r
4 * This file is part of CasparCG (www.casparcg.com).
\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
19 * Author: Nicklas P Andersson
\r
22 #include "../StdAfx.h"
\r
25 #include <common/exception/win32_exception.h>
\r
29 Event::Event(bool bManualReset, bool bInitialState) : handle_(0)
\r
31 handle_ = CreateEvent(0, bManualReset, bInitialState, 0);
\r
33 throw std::exception("Failed to create event");
\r
40 //BOOL res = SetEvent(handle_);
\r
41 //if(res == FALSE) {
\r
42 // DWORD error = GetLastError();
\r
45 void Event::Reset() {
\r
46 ResetEvent(handle_);
\r
51 CloseHandle(handle_);
\r
54 bool Thread::static_bInstallWin32ExceptionHandler_ = true;
\r
56 Thread::Thread() : pRunnable_(0), hThread_(0), stopEvent_(TRUE, FALSE), timeout_(10000) {
\r
63 bool Thread::IsRunning() {
\r
65 if(WaitForSingleObject(hThread_, 0) == WAIT_OBJECT_0) {
\r
66 CloseHandle(hThread_);
\r
72 return (hThread_ != 0);
\r
75 bool Thread::Start(IRunnable* pRunnable) {
\r
77 if(pRunnable != 0) {
\r
78 pRunnable_ = pRunnable;
\r
80 hThread_ = CreateThread(0, 0, ThreadEntrypoint, this, 0, 0);
\r
85 return (hThread_ != 0);
\r
91 bool Thread::Stop(bool bWait) {
\r
92 bool returnValue = true;
\r
98 DWORD successCode = WaitForSingleObject(hThread_, timeout_);
\r
99 if(successCode != WAIT_OBJECT_0)
\r
100 returnValue = false;
\r
102 CloseHandle(hThread_);
\r
108 return returnValue;
\r
111 void Thread::EnableWin32ExceptionHandler(bool bEnable) {
\r
112 static_bInstallWin32ExceptionHandler_ = bEnable;
\r
115 DWORD WINAPI Thread::ThreadEntrypoint(LPVOID pParam) {
\r
116 Thread* pThis = reinterpret_cast<Thread*>(pParam);
\r
118 if(Thread::static_bInstallWin32ExceptionHandler_)
\r
119 win32_exception::install_handler();
\r
121 _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
\r
128 void Thread::Run() {
\r
129 bool bDoRestart = false;
\r
133 bDoRestart = false;
\r
134 stopEvent_.Reset();
\r
135 pRunnable_->Run(stopEvent_);
\r
137 catch(const std::exception& e) {
\r
138 bDoRestart = pRunnable_->OnUnhandledException(e);
\r
140 }while(bDoRestart);
\r