/*----------------------------------------------------------------------------- * thread.cpp * Copyright (C) 2003, 2004, 2005 Akito Nozaki * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include #include #include NAMESPACE_TANOSHI { ThreadPrivate::ThreadPrivate() { running = false; finished = true; } void *ThreadPrivate::start(void *arg) { Thread *td = reinterpret_cast(arg); ThreadPrivate *d = td->d; d->running = true; d->finished = false; td->run(); pthread_exit(0); } Thread::Thread() : d(new ThreadPrivate) { } Thread::~Thread() { if(d->running && !d->finished) { // thread is still running... this will cause a crash. } delete d; } bool Thread::isTerminated() { d->locker.readLock(); bool t = (d->finished == true); d->locker.readWriteUnlock(); return t; } bool Thread::isRunning() { d->locker.readLock(); bool t = (d->running == true); d->locker.readWriteUnlock(); return t; } void Thread::start() { d->locker.writeLock(); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); // TODO the Atribute should probably be set... priority etc. pthread_create(&d->thread_id, &attr, ThreadPrivate::start, this); pthread_attr_destroy(&attr); d->locker.readWriteUnlock(); started(); } void Thread::terminate() { d->locker.writeLock(); if(d->thread_id) { d->finished = true; int code=pthread_cancel(d->thread_id); if(!code) d->finished = true; } d->locker.readWriteUnlock(); terminated(); } unsigned int Thread::thisThreadId() { return (unsigned int)pthread_self(); } }