2 * Copyright 2013 Sveriges Television AB http://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 Thread::Thread() : pRunnable_(0), hThread_(0), stopEvent_(TRUE, FALSE), timeout_(10000) {
\r
61 bool Thread::IsRunning() {
\r
63 if(WaitForSingleObject(hThread_, 0) == WAIT_OBJECT_0) {
\r
64 CloseHandle(hThread_);
\r
70 return (hThread_ != 0);
\r
73 bool Thread::Start(IRunnable* pRunnable) {
\r
75 if(pRunnable != 0) {
\r
76 pRunnable_ = pRunnable;
\r
78 hThread_ = CreateThread(0, 0, ThreadEntrypoint, this, 0, 0);
\r
83 return (hThread_ != 0);
\r
89 bool Thread::Stop(bool bWait) {
\r
90 bool returnValue = true;
\r
96 DWORD successCode = WaitForSingleObject(hThread_, timeout_);
\r
97 if(successCode != WAIT_OBJECT_0)
\r
98 returnValue = false;
\r
100 CloseHandle(hThread_);
\r
106 return returnValue;
\r
109 DWORD WINAPI Thread::ThreadEntrypoint(LPVOID pParam) {
\r
110 Thread* pThis = reinterpret_cast<Thread*>(pParam);
\r
112 win32_exception::install_handler();
\r
114 _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
\r
121 void Thread::Run() {
\r
122 bool bDoRestart = false;
\r
126 bDoRestart = false;
\r
127 stopEvent_.Reset();
\r
128 pRunnable_->Run(stopEvent_);
\r
130 catch(const std::exception& e) {
\r
131 bDoRestart = pRunnable_->OnUnhandledException(e);
\r
133 }while(bDoRestart);
\r