75812b334baf8891d120979b335a1ec1c6d1bfe9
[clinton/bobotpp.git] / source / BotThreading.C
1 // BotThreading.C -*- C++ -*-
2 // Copyright (c) 2008 Clinton Ebadi
3
4 // This program is free software; you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation; either version 2 of the License, or
7 // any later version.
8
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 // 02110-1301, USA.
18
19 #include "BotThreading.H"
20
21 #ifdef MULTITHREAD
22
23 #include <pthread.h>
24 #include <iostream>
25
26 BotMutex::BotMutex (bool recursive)
27 {
28 pthread_t self = pthread_self ();
29 std::cerr << "Mutex Init..."
30 << " Mutex: " << &mutex
31 << " Thread: " << &self
32 << std::endl;
33 pthread_mutexattr_init (&attrs);
34
35 if (recursive)
36 pthread_mutexattr_settype (&attrs, PTHREAD_MUTEX_RECURSIVE);
37
38 pthread_mutex_init (&mutex, &attrs);
39
40 }
41
42 BotMutex::~BotMutex ()
43 {
44 pthread_t self = pthread_self ();
45 std::cerr << "Mutex Destroy..."
46 << " Mutex: " << &mutex
47 << " Thread: " << &self
48 << std::endl;
49 pthread_mutex_destroy (&mutex);
50 pthread_mutexattr_destroy (&attrs);
51 }
52
53 void BotMutex::lock ()
54 {
55 pthread_t self = pthread_self ();
56 std::cerr << "< Mutex Lock..."
57 << " Mutex: " << &mutex
58 << " Thread: " << &self
59 << std::endl;
60 pthread_mutex_lock (&mutex);
61 }
62
63 void BotMutex::unlock ()
64 {
65 pthread_t self = pthread_self ();
66 std::cerr << "> Mutex Unlock..."
67 << " Mutex: " << &mutex
68 << " Thread: " << &self
69 << std::endl;
70 pthread_mutex_unlock (&mutex);
71 }
72
73 #else // non threaded noops
74
75 BotMutex::BotMutex ()
76 { }
77
78 BotMutex::~BotMutex ()
79 { }
80
81 void BotMutex::lock ()
82 { }
83
84 void BotMutex::unlock ()
85 { }
86
87 #endif // MULTITHREAD
88
89 BotLock::BotLock (BotMutex & m)
90 : mutex(m)
91 {
92 pthread_t self = pthread_self ();
93 std::cerr << "Lock Init..."
94 << " Lock: " << this
95 << " Mutex: " << &mutex
96 << " Thread: " << &self
97 << std::endl;
98 mutex.lock ();
99 }
100
101 BotLock::~BotLock ()
102 {
103 pthread_t self = pthread_self ();
104 std::cerr << "Lock Destroy..."
105 << " Lock: " << this
106 << " Mutex: " << &mutex
107 << " Thread: " << &self
108 << std::endl;
109 mutex.unlock ();
110 }