1 /* thread.cc
2  * This file belongs to Worker, a file manager for UN*X/X11.
3  * Copyright (C) 2006,2016 Ralf Hoffmann.
4  * You can contact me at: ralf@boomerangsworld.de
5  *   or http://www.boomerangsworld.de/worker
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21 
22 #include "thread.hh"
23 
Thread()24 Thread::Thread() : _id( 0 ), m_running( false ), m_cancel( false )
25 {
26 }
27 
~Thread()28 Thread::~Thread()
29 {
30   join();
31 }
32 
start()33 int Thread::start()
34 {
35   int erg;
36 
37   // lock var so actual run() only starts after _id is stored
38   _lock.lock();
39   m_running = true;
40   erg = pthread_create( &_id, NULL, thread_entry, this );
41   _lock.unlock();
42   return erg;
43 }
44 
thread_entry(void * me)45 void *Thread::thread_entry( void *me )
46 {
47     ((Thread*)me)->thread_run();
48     return NULL;
49 }
50 
join()51 int Thread::join()
52 {
53   int erg = 0;
54 
55   if ( _id != 0 ) {
56     erg = pthread_join( _id, NULL );
57     _id = 0;
58   }
59   return erg;
60 }
61 
amIThisThread() const62 bool Thread::amIThisThread() const
63 {
64   if ( pthread_equal( _id, pthread_self() ) )
65     return true;
66   return false;
67 }
68 
thread_run()69 void Thread::thread_run()
70 {
71     _lock.lock();
72     _lock.unlock();
73     // after having got the lock _id is correct so amIThisThread works
74     run();
75     _lock.lock();
76     m_running = false;
77     _lock.unlock();
78 }
79 
running()80 bool Thread::running()
81 {
82     return m_running;
83 }
84 
signalCancel()85 void Thread::signalCancel()
86 {
87     m_cancel = true;
88 }
89 
isCanceled()90 bool Thread::isCanceled()
91 {
92     return m_cancel;
93 }
94