//  // // ##### #### # # -= Threadux =-  // //  # # # ## ## Thread.cpp  // //  # # # ##  // //  # # # ### Thread creation and management  // //  # # # ## ##  // //  # #### # # R1 2004 by Markus Ewald  // //  // #include "Threadux/Thread.h" using namespace Threadux; #ifdef THREADUX_WIN32 // ############################################################################################# // // # Threadux::Thread::Thread() # // // ############################################################################################# // Thread::Thread() : m_pImpl(new Impl()), m_MaintenanceGate(false, true), m_bTerminateThread(false), m_pImpl(0) {} // ############################################################################################# // // # Threadux::Thread::wakeUp() # // // ############################################################################################# // /** Triggers the maintenance gate for the thread. This should be used if the thread runs out of work but has to keep running. It will also be triggered by the terminate() method in order to make sure that the thread notices the termination request */ void Thread::wakeUp() { m_MaintenanceGate.open(); } // ############################################################################################# // // # Threadux::Thread::start() # // // ############################################################################################# // /** Begins executing the thread. If the thread was already running at the time this method is called, it is terminated and started over again. */ void Thread::start() { terminate(); m_bTerminateThread = false; // Create a new thread for blocking on all registered socket's events HANDLE hThread = ::CreateThread(NULL, 0, threadProc, this, 0, &m_ThreadID); if(!hThread) throw runtime_error("Failed to create new thread"); m_pImpl = reinterpret_cast(hThread); } // ############################################################################################# // // # Threadux::Thread::terminate() # // // ############################################################################################# // /** Terminates the thread. When the number of milliseconds specified as the timeout has expired, the thread is forcefully terminated @param Timeout Timeout after which to forcefully terminate the thread */ void Thread::terminate(size_t Timeout) { if(m_pImpl) { m_bTerminateThread = true; wakeUp(); HANDLE hThread = reinterpret_cast(m_pImpl); if(::WaitForSingleObject(hThread, static_cast(Timeout)) == WAIT_TIMEOUT) ::TerminateThread(m_hThread, EXIT_FAILURE); ::CloseHandle(hThread); m_pImpl = NULL; } } #endif // THREADUX_WIN32