Thread.cpp

Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2006-2010 Jacek Sieka, arnetheduck on gmail point com
00003  *
00004  * This program is free software; you can redistribute it and/or modify
00005  * it under the terms of the GNU General Public License as published by
00006  * the Free Software Foundation; either version 2 of the License, or
00007  * (at your option) any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful,
00010  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012  * GNU General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software
00016  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
00017  */
00018 
00019 #include "adchpp.h"
00020 
00021 #include "Thread.h"
00022 #include "Util.h"
00023 
00024 namespace adchpp {
00025 
00026 
00027 #ifdef _WIN32
00028 
00029 void Thread::start() throw(ThreadException) {
00030     if(isRunning()) {
00031         throw ThreadException(_T("Already running"));
00032     }
00033 
00034     DWORD threadId = 0;
00035     if( (threadHandle = ::CreateThread(NULL, 0, &starter, this, 0, &threadId)) == NULL) {
00036         throw ThreadException(Util::translateError(::GetLastError()));
00037     }
00038 }
00039 
00040 void Thread::join() throw() {
00041     if(!isRunning()) {
00042         return;
00043     }
00044 
00045     ::WaitForSingleObject(threadHandle, INFINITE);
00046     ::CloseHandle(threadHandle);
00047     threadHandle = INVALID_HANDLE_VALUE;
00048 }
00049 
00050 #else // _WIN32
00051 
00052 void Thread::start() throw(ThreadException) {
00053     if(isRunning()) {
00054         throw ThreadException(_T("Already running"));
00055     }
00056 
00057     // Not all implementations may create threads as joinable by default.
00058     pthread_attr_t attr;
00059     pthread_attr_init(&attr);
00060     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
00061     int result = pthread_create(&t, &attr, &starter, this);
00062     if(result != 0) {
00063         throw ThreadException(Util::translateError(result));
00064     }
00065     pthread_attr_destroy(&attr);
00066 }
00067 
00068 void Thread::join() throw() {
00069     if(t == 0)
00070         return;
00071 
00072     void* x;
00073     pthread_join(t, &x);
00074     t = 0;
00075 }
00076 
00077 #endif
00078 }
00079 
Generated on Sat Nov 27 23:37:53 2010 for adchpp by  doxygen 1.6.3