1 /* Locking in multithreaded situations.
2 Copyright (C) 2005-2007 Free Software Foundation, Inc.
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, or (at your option)
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.
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 Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Written by Bruno Haible <bruno@clisp.org>, 2005.
19 Based on GCC's gthr-posix.h, gthr-posix95.h, gthr-solaris.h,
26 /* ========================================================================= */
30 /* Use the POSIX threads library. */
32 # if PTHREAD_IN_USE_DETECTION_HARD
34 /* The function to be executed by a dummy thread. */
36 dummy_thread_func (void *arg)
42 glthread_in_use (void)
45 static int result; /* 1: linked with -lpthread, 0: only with libc */
51 if (pthread_create (&thread, NULL, dummy_thread_func, NULL) != 0)
52 /* Thread creation failed. */
56 /* Thread creation works. */
58 if (pthread_join (thread, &retval) != 0)
69 /* -------------------------- gl_lock_t datatype -------------------------- */
71 /* ------------------------- gl_rwlock_t datatype ------------------------- */
73 # if HAVE_PTHREAD_RWLOCK
75 # if !defined PTHREAD_RWLOCK_INITIALIZER
78 glthread_rwlock_init (gl_rwlock_t *lock)
80 if (pthread_rwlock_init (&lock->rwlock, NULL) != 0)
82 lock->initialized = 1;
86 glthread_rwlock_rdlock (gl_rwlock_t *lock)
88 if (!lock->initialized)
90 if (pthread_mutex_lock (&lock->guard) != 0)
92 if (!lock->initialized)
93 glthread_rwlock_init (lock);
94 if (pthread_mutex_unlock (&lock->guard) != 0)
97 if (pthread_rwlock_rdlock (&lock->rwlock) != 0)
102 glthread_rwlock_wrlock (gl_rwlock_t *lock)
104 if (!lock->initialized)
106 if (pthread_mutex_lock (&lock->guard) != 0)
108 if (!lock->initialized)
109 glthread_rwlock_init (lock);
110 if (pthread_mutex_unlock (&lock->guard) != 0)
113 if (pthread_rwlock_wrlock (&lock->rwlock) != 0)
118 glthread_rwlock_unlock (gl_rwlock_t *lock)
120 if (!lock->initialized)
122 if (pthread_rwlock_unlock (&lock->rwlock) != 0)
127 glthread_rwlock_destroy (gl_rwlock_t *lock)
129 if (!lock->initialized)
131 if (pthread_rwlock_destroy (&lock->rwlock) != 0)
133 lock->initialized = 0;
141 glthread_rwlock_init (gl_rwlock_t *lock)
143 if (pthread_mutex_init (&lock->lock, NULL) != 0)
145 if (pthread_cond_init (&lock->waiting_readers, NULL) != 0)
147 if (pthread_cond_init (&lock->waiting_writers, NULL) != 0)
149 lock->waiting_writers_count = 0;
154 glthread_rwlock_rdlock (gl_rwlock_t *lock)
156 if (pthread_mutex_lock (&lock->lock) != 0)
158 /* Test whether only readers are currently running, and whether the runcount
159 field will not overflow. */
160 /* POSIX says: "It is implementation-defined whether the calling thread
161 acquires the lock when a writer does not hold the lock and there are
162 writers blocked on the lock." Let's say, no: give the writers a higher
164 while (!(lock->runcount + 1 > 0 && lock->waiting_writers_count == 0))
166 /* This thread has to wait for a while. Enqueue it among the
168 if (pthread_cond_wait (&lock->waiting_readers, &lock->lock) != 0)
172 if (pthread_mutex_unlock (&lock->lock) != 0)
177 glthread_rwlock_wrlock (gl_rwlock_t *lock)
179 if (pthread_mutex_lock (&lock->lock) != 0)
181 /* Test whether no readers or writers are currently running. */
182 while (!(lock->runcount == 0))
184 /* This thread has to wait for a while. Enqueue it among the
186 lock->waiting_writers_count++;
187 if (pthread_cond_wait (&lock->waiting_writers, &lock->lock) != 0)
189 lock->waiting_writers_count--;
191 lock->runcount--; /* runcount becomes -1 */
192 if (pthread_mutex_unlock (&lock->lock) != 0)
197 glthread_rwlock_unlock (gl_rwlock_t *lock)
199 if (pthread_mutex_lock (&lock->lock) != 0)
201 if (lock->runcount < 0)
203 /* Drop a writer lock. */
204 if (!(lock->runcount == -1))
210 /* Drop a reader lock. */
211 if (!(lock->runcount > 0))
215 if (lock->runcount == 0)
217 /* POSIX recommends that "write locks shall take precedence over read
218 locks", to avoid "writer starvation". */
219 if (lock->waiting_writers_count > 0)
221 /* Wake up one of the waiting writers. */
222 if (pthread_cond_signal (&lock->waiting_writers) != 0)
227 /* Wake up all waiting readers. */
228 if (pthread_cond_broadcast (&lock->waiting_readers) != 0)
232 if (pthread_mutex_unlock (&lock->lock) != 0)
237 glthread_rwlock_destroy (gl_rwlock_t *lock)
239 if (pthread_mutex_destroy (&lock->lock) != 0)
241 if (pthread_cond_destroy (&lock->waiting_readers) != 0)
243 if (pthread_cond_destroy (&lock->waiting_writers) != 0)
249 /* --------------------- gl_recursive_lock_t datatype --------------------- */
251 # if HAVE_PTHREAD_MUTEX_RECURSIVE
253 # if defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER || defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
256 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
258 pthread_mutexattr_t attributes;
260 if (pthread_mutexattr_init (&attributes) != 0)
262 if (pthread_mutexattr_settype (&attributes, PTHREAD_MUTEX_RECURSIVE) != 0)
264 if (pthread_mutex_init (lock, &attributes) != 0)
266 if (pthread_mutexattr_destroy (&attributes) != 0)
273 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
275 pthread_mutexattr_t attributes;
277 if (pthread_mutexattr_init (&attributes) != 0)
279 if (pthread_mutexattr_settype (&attributes, PTHREAD_MUTEX_RECURSIVE) != 0)
281 if (pthread_mutex_init (&lock->recmutex, &attributes) != 0)
283 if (pthread_mutexattr_destroy (&attributes) != 0)
285 lock->initialized = 1;
289 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
291 if (!lock->initialized)
293 if (pthread_mutex_lock (&lock->guard) != 0)
295 if (!lock->initialized)
296 glthread_recursive_lock_init (lock);
297 if (pthread_mutex_unlock (&lock->guard) != 0)
300 if (pthread_mutex_lock (&lock->recmutex) != 0)
305 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
307 if (!lock->initialized)
309 if (pthread_mutex_unlock (&lock->recmutex) != 0)
314 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
316 if (!lock->initialized)
318 if (pthread_mutex_destroy (&lock->recmutex) != 0)
320 lock->initialized = 0;
328 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
330 if (pthread_mutex_init (&lock->mutex, NULL) != 0)
332 lock->owner = (pthread_t) 0;
337 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
339 pthread_t self = pthread_self ();
340 if (lock->owner != self)
342 if (pthread_mutex_lock (&lock->mutex) != 0)
346 if (++(lock->depth) == 0) /* wraparound? */
351 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
353 if (lock->owner != pthread_self ())
355 if (lock->depth == 0)
357 if (--(lock->depth) == 0)
359 lock->owner = (pthread_t) 0;
360 if (pthread_mutex_unlock (&lock->mutex) != 0)
366 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
368 if (lock->owner != (pthread_t) 0)
370 if (pthread_mutex_destroy (&lock->mutex) != 0)
376 /* -------------------------- gl_once_t datatype -------------------------- */
378 static const pthread_once_t fresh_once = PTHREAD_ONCE_INIT;
381 glthread_once_singlethreaded (pthread_once_t *once_control)
383 /* We don't know whether pthread_once_t is an integer type, a floating-point
384 type, a pointer type, or a structure type. */
385 char *firstbyte = (char *)once_control;
386 if (*firstbyte == *(const char *)&fresh_once)
388 /* First time use of once_control. Invert the first byte. */
389 *firstbyte = ~ *(const char *)&fresh_once;
398 /* ========================================================================= */
402 /* Use the GNU Pth threads library. */
404 /* -------------------------- gl_lock_t datatype -------------------------- */
406 /* ------------------------- gl_rwlock_t datatype ------------------------- */
408 /* --------------------- gl_recursive_lock_t datatype --------------------- */
410 /* -------------------------- gl_once_t datatype -------------------------- */
413 glthread_once_call (void *arg)
415 void (**gl_once_temp_addr) (void) = (void (**) (void)) arg;
416 void (*initfunction) (void) = *gl_once_temp_addr;
421 glthread_once_singlethreaded (pth_once_t *once_control)
423 /* We know that pth_once_t is an integer type. */
424 if (*once_control == PTH_ONCE_INIT)
426 /* First time use of once_control. Invert the marker. */
427 *once_control = ~ PTH_ONCE_INIT;
436 /* ========================================================================= */
438 #if USE_SOLARIS_THREADS
440 /* Use the old Solaris threads library. */
442 /* -------------------------- gl_lock_t datatype -------------------------- */
444 /* ------------------------- gl_rwlock_t datatype ------------------------- */
446 /* --------------------- gl_recursive_lock_t datatype --------------------- */
449 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
451 if (mutex_init (&lock->mutex, USYNC_THREAD, NULL) != 0)
453 lock->owner = (thread_t) 0;
458 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
460 thread_t self = thr_self ();
461 if (lock->owner != self)
463 if (mutex_lock (&lock->mutex) != 0)
467 if (++(lock->depth) == 0) /* wraparound? */
472 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
474 if (lock->owner != thr_self ())
476 if (lock->depth == 0)
478 if (--(lock->depth) == 0)
480 lock->owner = (thread_t) 0;
481 if (mutex_unlock (&lock->mutex) != 0)
487 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
489 if (lock->owner != (thread_t) 0)
491 if (mutex_destroy (&lock->mutex) != 0)
495 /* -------------------------- gl_once_t datatype -------------------------- */
498 glthread_once (gl_once_t *once_control, void (*initfunction) (void))
500 if (!once_control->inited)
502 /* Use the mutex to guarantee that if another thread is already calling
503 the initfunction, this thread waits until it's finished. */
504 if (mutex_lock (&once_control->mutex) != 0)
506 if (!once_control->inited)
508 once_control->inited = 1;
511 if (mutex_unlock (&once_control->mutex) != 0)
517 glthread_once_singlethreaded (gl_once_t *once_control)
519 /* We know that gl_once_t contains an integer type. */
520 if (!once_control->inited)
522 /* First time use of once_control. Invert the marker. */
523 once_control->inited = ~ 0;
532 /* ========================================================================= */
534 #if USE_WIN32_THREADS
536 /* -------------------------- gl_lock_t datatype -------------------------- */
539 glthread_lock_init (gl_lock_t *lock)
541 InitializeCriticalSection (&lock->lock);
542 lock->guard.done = 1;
546 glthread_lock_lock (gl_lock_t *lock)
548 if (!lock->guard.done)
550 if (InterlockedIncrement (&lock->guard.started) == 0)
551 /* This thread is the first one to need this lock. Initialize it. */
552 glthread_lock_init (lock);
554 /* Yield the CPU while waiting for another thread to finish
555 initializing this lock. */
556 while (!lock->guard.done)
559 EnterCriticalSection (&lock->lock);
563 glthread_lock_unlock (gl_lock_t *lock)
565 if (!lock->guard.done)
567 LeaveCriticalSection (&lock->lock);
571 glthread_lock_destroy (gl_lock_t *lock)
573 if (!lock->guard.done)
575 DeleteCriticalSection (&lock->lock);
576 lock->guard.done = 0;
579 /* ------------------------- gl_rwlock_t datatype ------------------------- */
582 gl_waitqueue_init (gl_waitqueue_t *wq)
590 /* Enqueues the current thread, represented by an event, in a wait queue.
591 Returns INVALID_HANDLE_VALUE if an allocation failure occurs. */
593 gl_waitqueue_add (gl_waitqueue_t *wq)
598 if (wq->count == wq->alloc)
600 unsigned int new_alloc = 2 * wq->alloc + 1;
602 (HANDLE *) realloc (wq->array, new_alloc * sizeof (HANDLE));
603 if (new_array == NULL)
604 /* No more memory. */
605 return INVALID_HANDLE_VALUE;
606 /* Now is a good opportunity to rotate the array so that its contents
607 starts at offset 0. */
610 unsigned int old_count = wq->count;
611 unsigned int old_alloc = wq->alloc;
612 unsigned int old_offset = wq->offset;
614 if (old_offset + old_count > old_alloc)
616 unsigned int limit = old_offset + old_count - old_alloc;
617 for (i = 0; i < limit; i++)
618 new_array[old_alloc + i] = new_array[i];
620 for (i = 0; i < old_count; i++)
621 new_array[i] = new_array[old_offset + i];
624 wq->array = new_array;
625 wq->alloc = new_alloc;
627 event = CreateEvent (NULL, TRUE, FALSE, NULL);
628 if (event == INVALID_HANDLE_VALUE)
629 /* No way to allocate an event. */
630 return INVALID_HANDLE_VALUE;
631 index = wq->offset + wq->count;
632 if (index >= wq->alloc)
634 wq->array[index] = event;
639 /* Notifies the first thread from a wait queue and dequeues it. */
641 gl_waitqueue_notify_first (gl_waitqueue_t *wq)
643 SetEvent (wq->array[wq->offset + 0]);
646 if (wq->count == 0 || wq->offset == wq->alloc)
650 /* Notifies all threads from a wait queue and dequeues them all. */
652 gl_waitqueue_notify_all (gl_waitqueue_t *wq)
656 for (i = 0; i < wq->count; i++)
658 unsigned int index = wq->offset + i;
659 if (index >= wq->alloc)
661 SetEvent (wq->array[index]);
668 glthread_rwlock_init (gl_rwlock_t *lock)
670 InitializeCriticalSection (&lock->lock);
671 gl_waitqueue_init (&lock->waiting_readers);
672 gl_waitqueue_init (&lock->waiting_writers);
674 lock->guard.done = 1;
678 glthread_rwlock_rdlock (gl_rwlock_t *lock)
680 if (!lock->guard.done)
682 if (InterlockedIncrement (&lock->guard.started) == 0)
683 /* This thread is the first one to need this lock. Initialize it. */
684 glthread_rwlock_init (lock);
686 /* Yield the CPU while waiting for another thread to finish
687 initializing this lock. */
688 while (!lock->guard.done)
691 EnterCriticalSection (&lock->lock);
692 /* Test whether only readers are currently running, and whether the runcount
693 field will not overflow. */
694 if (!(lock->runcount + 1 > 0))
696 /* This thread has to wait for a while. Enqueue it among the
698 HANDLE event = gl_waitqueue_add (&lock->waiting_readers);
699 if (event != INVALID_HANDLE_VALUE)
702 LeaveCriticalSection (&lock->lock);
703 /* Wait until another thread signals this event. */
704 result = WaitForSingleObject (event, INFINITE);
705 if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
708 /* The thread which signalled the event already did the bookkeeping:
709 removed us from the waiting_readers, incremented lock->runcount. */
710 if (!(lock->runcount > 0))
716 /* Allocation failure. Weird. */
719 LeaveCriticalSection (&lock->lock);
721 EnterCriticalSection (&lock->lock);
723 while (!(lock->runcount + 1 > 0));
727 LeaveCriticalSection (&lock->lock);
731 glthread_rwlock_wrlock (gl_rwlock_t *lock)
733 if (!lock->guard.done)
735 if (InterlockedIncrement (&lock->guard.started) == 0)
736 /* This thread is the first one to need this lock. Initialize it. */
737 glthread_rwlock_init (lock);
739 /* Yield the CPU while waiting for another thread to finish
740 initializing this lock. */
741 while (!lock->guard.done)
744 EnterCriticalSection (&lock->lock);
745 /* Test whether no readers or writers are currently running. */
746 if (!(lock->runcount == 0))
748 /* This thread has to wait for a while. Enqueue it among the
750 HANDLE event = gl_waitqueue_add (&lock->waiting_writers);
751 if (event != INVALID_HANDLE_VALUE)
754 LeaveCriticalSection (&lock->lock);
755 /* Wait until another thread signals this event. */
756 result = WaitForSingleObject (event, INFINITE);
757 if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
760 /* The thread which signalled the event already did the bookkeeping:
761 removed us from the waiting_writers, set lock->runcount = -1. */
762 if (!(lock->runcount == -1))
768 /* Allocation failure. Weird. */
771 LeaveCriticalSection (&lock->lock);
773 EnterCriticalSection (&lock->lock);
775 while (!(lock->runcount == 0));
778 lock->runcount--; /* runcount becomes -1 */
779 LeaveCriticalSection (&lock->lock);
783 glthread_rwlock_unlock (gl_rwlock_t *lock)
785 if (!lock->guard.done)
787 EnterCriticalSection (&lock->lock);
788 if (lock->runcount < 0)
790 /* Drop a writer lock. */
791 if (!(lock->runcount == -1))
797 /* Drop a reader lock. */
798 if (!(lock->runcount > 0))
802 if (lock->runcount == 0)
804 /* POSIX recommends that "write locks shall take precedence over read
805 locks", to avoid "writer starvation". */
806 if (lock->waiting_writers.count > 0)
808 /* Wake up one of the waiting writers. */
810 gl_waitqueue_notify_first (&lock->waiting_writers);
814 /* Wake up all waiting readers. */
815 lock->runcount += lock->waiting_readers.count;
816 gl_waitqueue_notify_all (&lock->waiting_readers);
819 LeaveCriticalSection (&lock->lock);
823 glthread_rwlock_destroy (gl_rwlock_t *lock)
825 if (!lock->guard.done)
827 if (lock->runcount != 0)
829 DeleteCriticalSection (&lock->lock);
830 if (lock->waiting_readers.array != NULL)
831 free (lock->waiting_readers.array);
832 if (lock->waiting_writers.array != NULL)
833 free (lock->waiting_writers.array);
834 lock->guard.done = 0;
837 /* --------------------- gl_recursive_lock_t datatype --------------------- */
840 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
844 InitializeCriticalSection (&lock->lock);
845 lock->guard.done = 1;
849 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
851 if (!lock->guard.done)
853 if (InterlockedIncrement (&lock->guard.started) == 0)
854 /* This thread is the first one to need this lock. Initialize it. */
855 glthread_recursive_lock_init (lock);
857 /* Yield the CPU while waiting for another thread to finish
858 initializing this lock. */
859 while (!lock->guard.done)
863 DWORD self = GetCurrentThreadId ();
864 if (lock->owner != self)
866 EnterCriticalSection (&lock->lock);
869 if (++(lock->depth) == 0) /* wraparound? */
875 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
877 if (lock->owner != GetCurrentThreadId ())
879 if (lock->depth == 0)
881 if (--(lock->depth) == 0)
884 LeaveCriticalSection (&lock->lock);
889 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
891 if (lock->owner != 0)
893 DeleteCriticalSection (&lock->lock);
894 lock->guard.done = 0;
897 /* -------------------------- gl_once_t datatype -------------------------- */
900 glthread_once (gl_once_t *once_control, void (*initfunction) (void))
902 if (once_control->inited <= 0)
904 if (InterlockedIncrement (&once_control->started) == 0)
906 /* This thread is the first one to come to this once_control. */
907 InitializeCriticalSection (&once_control->lock);
908 EnterCriticalSection (&once_control->lock);
909 once_control->inited = 0;
911 once_control->inited = 1;
912 LeaveCriticalSection (&once_control->lock);
916 /* Undo last operation. */
917 InterlockedDecrement (&once_control->started);
918 /* Some other thread has already started the initialization.
919 Yield the CPU while waiting for the other thread to finish
920 initializing and taking the lock. */
921 while (once_control->inited < 0)
923 if (once_control->inited <= 0)
925 /* Take the lock. This blocks until the other thread has
926 finished calling the initfunction. */
927 EnterCriticalSection (&once_control->lock);
928 LeaveCriticalSection (&once_control->lock);
929 if (!(once_control->inited > 0))
938 /* ========================================================================= */