4 * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #include "bcsignals.h"
30 Mutex::Mutex(const char *title, int recursive)
34 pthread_mutexattr_t attr;
35 pthread_mutexattr_init(&attr);
36 pthread_mutex_init(&mutex, &attr);
37 pthread_mutex_init(&recursive_lock, &attr);
39 this->recursive = recursive;
46 pthread_mutex_destroy(&mutex);
47 pthread_mutex_destroy(&recursive_lock);
48 UNSET_ALL_LOCKS(this);
51 int Mutex::lock(const char *location)
53 // Test recursive owner and give up if we already own it
56 pthread_mutex_lock(&recursive_lock);
57 if(thread_id_valid && pthread_self() == thread_id)
60 pthread_mutex_unlock(&recursive_lock);
63 pthread_mutex_unlock(&recursive_lock);
67 SET_LOCK(this, title, location);
68 if(pthread_mutex_lock(&mutex)) perror("Mutex::lock");
72 // Update recursive status for the first lock
75 pthread_mutex_lock(&recursive_lock);
77 thread_id = pthread_self();
79 pthread_mutex_unlock(&recursive_lock);
94 printf("Mutex::unlock not locked: %s\n", title);
97 // Remove from recursive status
100 pthread_mutex_lock(&recursive_lock);
105 pthread_mutex_unlock(&recursive_lock);
111 pthread_mutex_unlock(&recursive_lock);
119 int ret = pthread_mutex_unlock(&mutex);
120 if( ret ) fprintf(stderr, "Mutex::unlock: %s\n",strerror(ret));
124 int Mutex::trylock(const char *location)
126 if( count ) return EBUSY;
127 int ret = pthread_mutex_trylock(&mutex);
128 if( ret ) return ret;
130 // Update recursive status for the first lock
132 pthread_mutex_lock(&recursive_lock);
134 thread_id = pthread_self();
136 pthread_mutex_unlock(&recursive_lock);
141 SET_LOCK(this, title, location);
146 int Mutex::is_locked()
153 pthread_mutex_destroy(&mutex);
154 pthread_mutexattr_t attr;
155 pthread_mutexattr_init(&attr);
156 pthread_mutex_init(&mutex, &attr);
157 UNSET_ALL_LOCKS(this)