1 /* Locking in multithreaded situations.
2 Copyright (C) 2005-2006 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->recmutex, &attributes) != 0)
266 if (pthread_mutexattr_destroy (&attributes) != 0)
268 lock->initialized = 1;
272 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
274 if (!lock->initialized)
276 if (pthread_mutex_lock (&lock->guard) != 0)
278 if (!lock->initialized)
279 glthread_recursive_lock_init (lock);
280 if (pthread_mutex_unlock (&lock->guard) != 0)
283 if (pthread_mutex_lock (&lock->recmutex) != 0)
288 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
290 if (!lock->initialized)
292 if (pthread_mutex_unlock (&lock->recmutex) != 0)
297 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
299 if (!lock->initialized)
301 if (pthread_mutex_destroy (&lock->recmutex) != 0)
303 lock->initialized = 0;
311 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
313 if (pthread_mutex_init (&lock->mutex, NULL) != 0)
315 lock->owner = (pthread_t) 0;
320 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
322 pthread_t self = pthread_self ();
323 if (lock->owner != self)
325 if (pthread_mutex_lock (&lock->mutex) != 0)
329 if (++(lock->depth) == 0) /* wraparound? */
334 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
336 if (lock->owner != pthread_self ())
338 if (lock->depth == 0)
340 if (--(lock->depth) == 0)
342 lock->owner = (pthread_t) 0;
343 if (pthread_mutex_unlock (&lock->mutex) != 0)
349 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
351 if (lock->owner != (pthread_t) 0)
353 if (pthread_mutex_destroy (&lock->mutex) != 0)
359 /* -------------------------- gl_once_t datatype -------------------------- */
361 static const pthread_once_t fresh_once = PTHREAD_ONCE_INIT;
364 glthread_once_singlethreaded (pthread_once_t *once_control)
366 /* We don't know whether pthread_once_t is an integer type, a floating-point
367 type, a pointer type, or a structure type. */
368 char *firstbyte = (char *)once_control;
369 if (*firstbyte == *(const char *)&fresh_once)
371 /* First time use of once_control. Invert the first byte. */
372 *firstbyte = ~ *(const char *)&fresh_once;
381 /* ========================================================================= */
385 /* Use the GNU Pth threads library. */
387 /* -------------------------- gl_lock_t datatype -------------------------- */
389 /* ------------------------- gl_rwlock_t datatype ------------------------- */
391 /* --------------------- gl_recursive_lock_t datatype --------------------- */
393 /* -------------------------- gl_once_t datatype -------------------------- */
396 glthread_once_call (void *arg)
398 void (**gl_once_temp_addr) (void) = (void (**) (void)) arg;
399 void (*initfunction) (void) = *gl_once_temp_addr;
404 glthread_once_singlethreaded (pth_once_t *once_control)
406 /* We know that pth_once_t is an integer type. */
407 if (*once_control == PTH_ONCE_INIT)
409 /* First time use of once_control. Invert the marker. */
410 *once_control = ~ PTH_ONCE_INIT;
419 /* ========================================================================= */
421 #if USE_SOLARIS_THREADS
423 /* Use the old Solaris threads library. */
425 /* -------------------------- gl_lock_t datatype -------------------------- */
427 /* ------------------------- gl_rwlock_t datatype ------------------------- */
429 /* --------------------- gl_recursive_lock_t datatype --------------------- */
432 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
434 if (mutex_init (&lock->mutex, USYNC_THREAD, NULL) != 0)
436 lock->owner = (thread_t) 0;
441 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
443 thread_t self = thr_self ();
444 if (lock->owner != self)
446 if (mutex_lock (&lock->mutex) != 0)
450 if (++(lock->depth) == 0) /* wraparound? */
455 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
457 if (lock->owner != thr_self ())
459 if (lock->depth == 0)
461 if (--(lock->depth) == 0)
463 lock->owner = (thread_t) 0;
464 if (mutex_unlock (&lock->mutex) != 0)
470 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
472 if (lock->owner != (thread_t) 0)
474 if (mutex_destroy (&lock->mutex) != 0)
478 /* -------------------------- gl_once_t datatype -------------------------- */
481 glthread_once (gl_once_t *once_control, void (*initfunction) (void))
483 if (!once_control->inited)
485 /* Use the mutex to guarantee that if another thread is already calling
486 the initfunction, this thread waits until it's finished. */
487 if (mutex_lock (&once_control->mutex) != 0)
489 if (!once_control->inited)
491 once_control->inited = 1;
494 if (mutex_unlock (&once_control->mutex) != 0)
500 glthread_once_singlethreaded (gl_once_t *once_control)
502 /* We know that gl_once_t contains an integer type. */
503 if (!once_control->inited)
505 /* First time use of once_control. Invert the marker. */
506 once_control->inited = ~ 0;
515 /* ========================================================================= */
517 #if USE_WIN32_THREADS
519 /* -------------------------- gl_lock_t datatype -------------------------- */
522 glthread_lock_init (gl_lock_t *lock)
524 InitializeCriticalSection (&lock->lock);
525 lock->guard.done = 1;
529 glthread_lock_lock (gl_lock_t *lock)
531 if (!lock->guard.done)
533 if (InterlockedIncrement (&lock->guard.started) == 0)
534 /* This thread is the first one to need this lock. Initialize it. */
535 glthread_lock_init (lock);
537 /* Yield the CPU while waiting for another thread to finish
538 initializing this lock. */
539 while (!lock->guard.done)
542 EnterCriticalSection (&lock->lock);
546 glthread_lock_unlock (gl_lock_t *lock)
548 if (!lock->guard.done)
550 LeaveCriticalSection (&lock->lock);
554 glthread_lock_destroy (gl_lock_t *lock)
556 if (!lock->guard.done)
558 DeleteCriticalSection (&lock->lock);
559 lock->guard.done = 0;
562 /* ------------------------- gl_rwlock_t datatype ------------------------- */
565 gl_waitqueue_init (gl_waitqueue_t *wq)
573 /* Enqueues the current thread, represented by an event, in a wait queue.
574 Returns INVALID_HANDLE_VALUE if an allocation failure occurs. */
576 gl_waitqueue_add (gl_waitqueue_t *wq)
581 if (wq->count == wq->alloc)
583 unsigned int new_alloc = 2 * wq->alloc + 1;
585 (HANDLE *) realloc (wq->array, new_alloc * sizeof (HANDLE));
586 if (new_array == NULL)
587 /* No more memory. */
588 return INVALID_HANDLE_VALUE;
589 /* Now is a good opportunity to rotate the array so that its contents
590 starts at offset 0. */
593 unsigned int old_count = wq->count;
594 unsigned int old_alloc = wq->alloc;
595 unsigned int old_offset = wq->offset;
597 if (old_offset + old_count > old_alloc)
599 unsigned int limit = old_offset + old_count - old_alloc;
600 for (i = 0; i < limit; i++)
601 new_array[old_alloc + i] = new_array[i];
603 for (i = 0; i < old_count; i++)
604 new_array[i] = new_array[old_offset + i];
607 wq->array = new_array;
608 wq->alloc = new_alloc;
610 event = CreateEvent (NULL, TRUE, FALSE, NULL);
611 if (event == INVALID_HANDLE_VALUE)
612 /* No way to allocate an event. */
613 return INVALID_HANDLE_VALUE;
614 index = wq->offset + wq->count;
615 if (index >= wq->alloc)
617 wq->array[index] = event;
622 /* Notifies the first thread from a wait queue and dequeues it. */
624 gl_waitqueue_notify_first (gl_waitqueue_t *wq)
626 SetEvent (wq->array[wq->offset + 0]);
629 if (wq->count == 0 || wq->offset == wq->alloc)
633 /* Notifies all threads from a wait queue and dequeues them all. */
635 gl_waitqueue_notify_all (gl_waitqueue_t *wq)
639 for (i = 0; i < wq->count; i++)
641 unsigned int index = wq->offset + i;
642 if (index >= wq->alloc)
644 SetEvent (wq->array[index]);
651 glthread_rwlock_init (gl_rwlock_t *lock)
653 InitializeCriticalSection (&lock->lock);
654 gl_waitqueue_init (&lock->waiting_readers);
655 gl_waitqueue_init (&lock->waiting_writers);
657 lock->guard.done = 1;
661 glthread_rwlock_rdlock (gl_rwlock_t *lock)
663 if (!lock->guard.done)
665 if (InterlockedIncrement (&lock->guard.started) == 0)
666 /* This thread is the first one to need this lock. Initialize it. */
667 glthread_rwlock_init (lock);
669 /* Yield the CPU while waiting for another thread to finish
670 initializing this lock. */
671 while (!lock->guard.done)
674 EnterCriticalSection (&lock->lock);
675 /* Test whether only readers are currently running, and whether the runcount
676 field will not overflow. */
677 if (!(lock->runcount + 1 > 0))
679 /* This thread has to wait for a while. Enqueue it among the
681 HANDLE event = gl_waitqueue_add (&lock->waiting_readers);
682 if (event != INVALID_HANDLE_VALUE)
685 LeaveCriticalSection (&lock->lock);
686 /* Wait until another thread signals this event. */
687 result = WaitForSingleObject (event, INFINITE);
688 if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
691 /* The thread which signalled the event already did the bookkeeping:
692 removed us from the waiting_readers, incremented lock->runcount. */
693 if (!(lock->runcount > 0))
699 /* Allocation failure. Weird. */
702 LeaveCriticalSection (&lock->lock);
704 EnterCriticalSection (&lock->lock);
706 while (!(lock->runcount + 1 > 0));
710 LeaveCriticalSection (&lock->lock);
714 glthread_rwlock_wrlock (gl_rwlock_t *lock)
716 if (!lock->guard.done)
718 if (InterlockedIncrement (&lock->guard.started) == 0)
719 /* This thread is the first one to need this lock. Initialize it. */
720 glthread_rwlock_init (lock);
722 /* Yield the CPU while waiting for another thread to finish
723 initializing this lock. */
724 while (!lock->guard.done)
727 EnterCriticalSection (&lock->lock);
728 /* Test whether no readers or writers are currently running. */
729 if (!(lock->runcount == 0))
731 /* This thread has to wait for a while. Enqueue it among the
733 HANDLE event = gl_waitqueue_add (&lock->waiting_writers);
734 if (event != INVALID_HANDLE_VALUE)
737 LeaveCriticalSection (&lock->lock);
738 /* Wait until another thread signals this event. */
739 result = WaitForSingleObject (event, INFINITE);
740 if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
743 /* The thread which signalled the event already did the bookkeeping:
744 removed us from the waiting_writers, set lock->runcount = -1. */
745 if (!(lock->runcount == -1))
751 /* Allocation failure. Weird. */
754 LeaveCriticalSection (&lock->lock);
756 EnterCriticalSection (&lock->lock);
758 while (!(lock->runcount == 0));
761 lock->runcount--; /* runcount becomes -1 */
762 LeaveCriticalSection (&lock->lock);
766 glthread_rwlock_unlock (gl_rwlock_t *lock)
768 if (!lock->guard.done)
770 EnterCriticalSection (&lock->lock);
771 if (lock->runcount < 0)
773 /* Drop a writer lock. */
774 if (!(lock->runcount == -1))
780 /* Drop a reader lock. */
781 if (!(lock->runcount > 0))
785 if (lock->runcount == 0)
787 /* POSIX recommends that "write locks shall take precedence over read
788 locks", to avoid "writer starvation". */
789 if (lock->waiting_writers.count > 0)
791 /* Wake up one of the waiting writers. */
793 gl_waitqueue_notify_first (&lock->waiting_writers);
797 /* Wake up all waiting readers. */
798 lock->runcount += lock->waiting_readers.count;
799 gl_waitqueue_notify_all (&lock->waiting_readers);
802 LeaveCriticalSection (&lock->lock);
806 glthread_rwlock_destroy (gl_rwlock_t *lock)
808 if (!lock->guard.done)
810 if (lock->runcount != 0)
812 DeleteCriticalSection (&lock->lock);
813 if (lock->waiting_readers.array != NULL)
814 free (lock->waiting_readers.array);
815 if (lock->waiting_writers.array != NULL)
816 free (lock->waiting_writers.array);
817 lock->guard.done = 0;
820 /* --------------------- gl_recursive_lock_t datatype --------------------- */
823 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
827 InitializeCriticalSection (&lock->lock);
828 lock->guard.done = 1;
832 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
834 if (!lock->guard.done)
836 if (InterlockedIncrement (&lock->guard.started) == 0)
837 /* This thread is the first one to need this lock. Initialize it. */
838 glthread_recursive_lock_init (lock);
840 /* Yield the CPU while waiting for another thread to finish
841 initializing this lock. */
842 while (!lock->guard.done)
846 DWORD self = GetCurrentThreadId ();
847 if (lock->owner != self)
849 EnterCriticalSection (&lock->lock);
852 if (++(lock->depth) == 0) /* wraparound? */
858 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
860 if (lock->owner != GetCurrentThreadId ())
862 if (lock->depth == 0)
864 if (--(lock->depth) == 0)
867 LeaveCriticalSection (&lock->lock);
872 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
874 if (lock->owner != 0)
876 DeleteCriticalSection (&lock->lock);
877 lock->guard.done = 0;
880 /* -------------------------- gl_once_t datatype -------------------------- */
883 glthread_once (gl_once_t *once_control, void (*initfunction) (void))
885 if (once_control->inited <= 0)
887 if (InterlockedIncrement (&once_control->started) == 0)
889 /* This thread is the first one to come to this once_control. */
890 InitializeCriticalSection (&once_control->lock);
891 EnterCriticalSection (&once_control->lock);
892 once_control->inited = 0;
894 once_control->inited = 1;
895 LeaveCriticalSection (&once_control->lock);
899 /* Undo last operation. */
900 InterlockedDecrement (&once_control->started);
901 /* Some other thread has already started the initialization.
902 Yield the CPU while waiting for the other thread to finish
903 initializing and taking the lock. */
904 while (once_control->inited < 0)
906 if (once_control->inited <= 0)
908 /* Take the lock. This blocks until the other thread has
909 finished calling the initfunction. */
910 EnterCriticalSection (&once_control->lock);
911 LeaveCriticalSection (&once_control->lock);
912 if (!(once_control->inited > 0))
921 /* ========================================================================= */