1 /* Locking in multithreaded situations.
2 Copyright (C) 2005 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify it
5 under the terms of the GNU Library General Public License as published
6 by 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 GNU
12 Library General Public License for more details.
14 You should have received a copy of the GNU Library General Public
15 License along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19 /* Written by Bruno Haible <bruno@clisp.org>, 2005.
20 Based on GCC's gthr-posix.h, gthr-posix95.h, gthr-solaris.h,
29 /* ========================================================================= */
33 /* Use the POSIX threads library. */
35 /* -------------------------- gl_lock_t datatype -------------------------- */
37 /* ------------------------- gl_rwlock_t datatype ------------------------- */
39 # if HAVE_PTHREAD_RWLOCK
41 # if !defined PTHREAD_RWLOCK_INITIALIZER
44 glthread_rwlock_init (gl_rwlock_t *lock)
46 if (pthread_rwlock_init (&lock->rwlock, NULL) != 0)
48 lock->initialized = 1;
52 glthread_rwlock_rdlock (gl_rwlock_t *lock)
54 if (!lock->initialized)
56 if (pthread_mutex_lock (&lock->guard) != 0)
58 if (!lock->initialized)
59 glthread_rwlock_init (lock);
60 if (pthread_mutex_unlock (&lock->guard) != 0)
63 if (pthread_rwlock_rdlock (&lock->rwlock) != 0)
68 glthread_rwlock_wrlock (gl_rwlock_t *lock)
70 if (!lock->initialized)
72 if (pthread_mutex_lock (&lock->guard) != 0)
74 if (!lock->initialized)
75 glthread_rwlock_init (lock);
76 if (pthread_mutex_unlock (&lock->guard) != 0)
79 if (pthread_rwlock_wrlock (&lock->rwlock) != 0)
84 glthread_rwlock_unlock (gl_rwlock_t *lock)
86 if (!lock->initialized)
88 if (pthread_rwlock_unlock (&lock->rwlock) != 0)
93 glthread_rwlock_destroy (gl_rwlock_t *lock)
95 if (!lock->initialized)
97 if (pthread_rwlock_destroy (&lock->rwlock) != 0)
99 lock->initialized = 0;
107 glthread_rwlock_init (gl_rwlock_t *lock)
109 if (pthread_mutex_init (&lock->lock, NULL) != 0)
111 if (pthread_cond_init (&lock->waiting_readers, NULL) != 0)
113 if (pthread_cond_init (&lock->waiting_writers, NULL) != 0)
115 lock->waiting_writers_count = 0;
120 glthread_rwlock_rdlock (gl_rwlock_t *lock)
122 if (pthread_mutex_lock (&lock->lock) != 0)
124 /* Test whether only readers are currently running, and whether the runcount
125 field will not overflow. */
126 /* POSIX says: "It is implementation-defined whether the calling thread
127 acquires the lock when a writer does not hold the lock and there are
128 writers blocked on the lock." Let's say, no: give the writers a higher
130 while (!(lock->runcount + 1 > 0 && lock->waiting_writers_count == 0))
132 /* This thread has to wait for a while. Enqueue it among the
134 if (pthread_cond_wait (&lock->waiting_readers, &lock->lock) != 0)
138 if (pthread_mutex_unlock (&lock->lock) != 0)
143 glthread_rwlock_wrlock (gl_rwlock_t *lock)
145 if (pthread_mutex_lock (&lock->lock) != 0)
147 /* Test whether no readers or writers are currently running. */
148 while (!(lock->runcount == 0))
150 /* This thread has to wait for a while. Enqueue it among the
152 lock->waiting_writers_count++;
153 if (pthread_cond_wait (&lock->waiting_writers, &lock->lock) != 0)
155 lock->waiting_writers_count--;
157 lock->runcount--; /* runcount becomes -1 */
158 if (pthread_mutex_unlock (&lock->lock) != 0)
163 glthread_rwlock_unlock (gl_rwlock_t *lock)
165 if (pthread_mutex_lock (&lock->lock) != 0)
167 if (lock->runcount < 0)
169 /* Drop a writer lock. */
170 if (!(lock->runcount == -1))
176 /* Drop a reader lock. */
177 if (!(lock->runcount > 0))
181 if (lock->runcount == 0)
183 /* POSIX recommends that "write locks shall take precedence over read
184 locks", to avoid "writer starvation". */
185 if (lock->waiting_writers_count > 0)
187 /* Wake up one of the waiting writers. */
188 if (pthread_cond_signal (&lock->waiting_writers) != 0)
193 /* Wake up all waiting readers. */
194 if (pthread_cond_broadcast (&lock->waiting_readers) != 0)
198 if (pthread_mutex_unlock (&lock->lock) != 0)
203 glthread_rwlock_destroy (gl_rwlock_t *lock)
205 if (pthread_mutex_destroy (&lock->lock) != 0)
207 if (pthread_cond_destroy (&lock->waiting_readers) != 0)
209 if (pthread_cond_destroy (&lock->waiting_writers) != 0)
215 /* --------------------- gl_recursive_lock_t datatype --------------------- */
217 # if HAVE_PTHREAD_MUTEX_RECURSIVE
219 # if !(defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER || defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
222 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
224 pthread_mutexattr_t attributes;
226 if (pthread_mutexattr_init (&attributes) != 0)
228 if (pthread_mutexattr_settype (&attributes, PTHREAD_MUTEX_RECURSIVE) != 0)
230 if (pthread_mutex_init (&lock->recmutex, &attributes) != 0)
232 if (pthread_mutexattr_destroy (&attributes) != 0)
234 lock->initialized = 1;
238 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
240 if (!lock->initialized)
242 if (pthread_mutex_lock (&lock->guard) != 0)
244 if (!lock->initialized)
245 glthread_recursive_lock_init (lock);
246 if (pthread_mutex_unlock (&lock->guard) != 0)
249 if (pthread_mutex_lock (&lock->recmutex) != 0)
254 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
256 if (!lock->initialized)
258 if (pthread_mutex_unlock (&lock->recmutex) != 0)
263 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
265 if (!lock->initialized)
267 if (pthread_mutex_destroy (&lock->recmutex) != 0)
269 lock->initialized = 0;
277 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
279 if (pthread_mutex_init (&lock->mutex, NULL) != 0)
281 lock->owner = (pthread_t) 0;
286 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
288 pthread_t self = pthread_self ();
289 if (lock->owner != self)
291 if (pthread_mutex_lock (&lock->mutex) != 0)
295 if (++(lock->depth) == 0) /* wraparound? */
300 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
302 if (lock->owner != pthread_self ())
304 if (lock->depth == 0)
306 if (--(lock->depth) == 0)
308 lock->owner = (pthread_t) 0;
309 if (pthread_mutex_unlock (&lock->mutex) != 0)
315 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
317 if (lock->owner != (pthread_t) 0)
319 if (pthread_mutex_destroy (&lock->mutex) != 0)
325 /* -------------------------- gl_once_t datatype -------------------------- */
327 static const pthread_once_t fresh_once = PTHREAD_ONCE_INIT;
330 glthread_once_singlethreaded (pthread_once_t *once_control)
332 /* We don't know whether pthread_once_t is an integer type, a floating-point
333 type, a pointer type, or a structure type. */
334 char *firstbyte = (char *)once_control;
335 if (*firstbyte == *(const char *)&fresh_once)
337 /* First time use of once_control. Invert the first byte. */
338 *firstbyte = ~ *(const char *)&fresh_once;
347 /* ========================================================================= */
351 /* Use the GNU Pth threads library. */
353 /* -------------------------- gl_lock_t datatype -------------------------- */
355 /* ------------------------- gl_rwlock_t datatype ------------------------- */
357 /* --------------------- gl_recursive_lock_t datatype --------------------- */
359 /* -------------------------- gl_once_t datatype -------------------------- */
362 glthread_once_call (void *arg)
364 void (**gl_once_temp_addr) (void) = (void (**) (void)) arg;
365 void (*initfunction) (void) = *gl_once_temp_addr;
370 glthread_once_singlethreaded (pth_once_t *once_control)
372 /* We know that pth_once_t is an integer type. */
373 if (*once_control == PTH_ONCE_INIT)
375 /* First time use of once_control. Invert the marker. */
376 *once_control = ~ PTH_ONCE_INIT;
385 /* ========================================================================= */
387 #if USE_SOLARIS_THREADS
389 /* Use the old Solaris threads library. */
391 /* -------------------------- gl_lock_t datatype -------------------------- */
393 /* ------------------------- gl_rwlock_t datatype ------------------------- */
395 /* --------------------- gl_recursive_lock_t datatype --------------------- */
398 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
400 if (mutex_init (&lock->mutex, USYNC_THREAD, NULL) != 0)
402 lock->owner = (thread_t) 0;
407 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
409 thread_t self = thr_self ();
410 if (lock->owner != self)
412 if (mutex_lock (&lock->mutex) != 0)
416 if (++(lock->depth) == 0) /* wraparound? */
421 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
423 if (lock->owner != thr_self ())
425 if (lock->depth == 0)
427 if (--(lock->depth) == 0)
429 lock->owner = (thread_t) 0;
430 if (mutex_unlock (&lock->mutex) != 0)
436 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
438 if (lock->owner != (thread_t) 0)
440 if (mutex_destroy (&lock->mutex) != 0)
444 /* -------------------------- gl_once_t datatype -------------------------- */
447 glthread_once (gl_once_t *once_control, void (*initfunction) (void))
449 if (!once_control->inited)
451 /* Use the mutex to guarantee that if another thread is already calling
452 the initfunction, this thread waits until it's finished. */
453 if (mutex_lock (&once_control->mutex) != 0)
455 if (!once_control->inited)
457 once_control->inited = 1;
460 if (mutex_unlock (&once_control->mutex) != 0)
466 glthread_once_singlethreaded (gl_once_t *once_control)
468 /* We know that gl_once_t contains an integer type. */
469 if (!once_control->inited)
471 /* First time use of once_control. Invert the marker. */
472 once_control->inited = ~ 0;
481 /* ========================================================================= */
483 #if USE_WIN32_THREADS
485 /* -------------------------- gl_lock_t datatype -------------------------- */
488 glthread_lock_init (gl_lock_t *lock)
490 InitializeCriticalSection (&lock->lock);
491 lock->guard.done = 1;
495 glthread_lock_lock (gl_lock_t *lock)
497 if (!lock->guard.done)
499 if (InterlockedIncrement (&lock->guard.started) == 0)
500 /* This thread is the first one to need this lock. Initialize it. */
501 glthread_lock_init (lock);
503 /* Yield the CPU while waiting for another thread to finish
504 initializing this lock. */
505 while (!lock->guard.done)
508 EnterCriticalSection (&lock->lock);
512 glthread_lock_unlock (gl_lock_t *lock)
514 if (!lock->guard.done)
516 LeaveCriticalSection (&lock->lock);
520 glthread_lock_destroy (gl_lock_t *lock)
522 if (!lock->guard.done)
524 DeleteCriticalSection (&lock->lock);
525 lock->guard.done = 0;
528 /* ------------------------- gl_rwlock_t datatype ------------------------- */
531 gl_waitqueue_init (gl_waitqueue_t *wq)
539 /* Enqueues the current thread, represented by an event, in a wait queue.
540 Returns INVALID_HANDLE_VALUE if an allocation failure occurs. */
542 gl_waitqueue_add (gl_waitqueue_t *wq)
547 if (wq->count == wq->alloc)
549 unsigned int new_alloc = 2 * wq->alloc + 1;
551 (HANDLE *) realloc (wq->array, new_alloc * sizeof (HANDLE));
552 if (new_array == NULL)
553 /* No more memory. */
554 return INVALID_HANDLE_VALUE;
555 /* Now is a good opportunity to rotate the array so that its contents
556 starts at offset 0. */
559 unsigned int old_count = wq->count;
560 unsigned int old_alloc = wq->alloc;
561 unsigned int old_offset = wq->offset;
563 if (old_offset + old_count > old_alloc)
565 unsigned int limit = old_offset + old_count - old_alloc;
566 for (i = 0; i < limit; i++)
567 new_array[old_alloc + i] = new_array[i];
569 for (i = 0; i < old_count; i++)
570 new_array[i] = new_array[old_offset + i];
573 wq->array = new_array;
574 wq->alloc = new_alloc;
576 event = CreateEvent (NULL, TRUE, FALSE, NULL);
577 if (event == INVALID_HANDLE_VALUE)
578 /* No way to allocate an event. */
579 return INVALID_HANDLE_VALUE;
580 index = wq->offset + wq->count;
581 if (index >= wq->alloc)
583 wq->array[index] = event;
588 /* Notifies the first thread from a wait queue and dequeues it. */
590 gl_waitqueue_notify_first (gl_waitqueue_t *wq)
592 SetEvent (wq->array[wq->offset + 0]);
595 if (wq->count == 0 || wq->offset == wq->alloc)
599 /* Notifies all threads from a wait queue and dequeues them all. */
601 gl_waitqueue_notify_all (gl_waitqueue_t *wq)
605 for (i = 0; i < wq->count; i++)
607 unsigned int index = wq->offset + i;
608 if (index >= wq->alloc)
610 SetEvent (wq->array[index]);
617 glthread_rwlock_init (gl_rwlock_t *lock)
619 InitializeCriticalSection (&lock->lock);
620 gl_waitqueue_init (&lock->waiting_readers);
621 gl_waitqueue_init (&lock->waiting_writers);
623 lock->guard.done = 1;
627 glthread_rwlock_rdlock (gl_rwlock_t *lock)
629 if (!lock->guard.done)
631 if (InterlockedIncrement (&lock->guard.started) == 0)
632 /* This thread is the first one to need this lock. Initialize it. */
633 glthread_rwlock_init (lock);
635 /* Yield the CPU while waiting for another thread to finish
636 initializing this lock. */
637 while (!lock->guard.done)
640 EnterCriticalSection (&lock->lock);
641 /* Test whether only readers are currently running, and whether the runcount
642 field will not overflow. */
643 if (!(lock->runcount + 1 > 0))
645 /* This thread has to wait for a while. Enqueue it among the
647 HANDLE event = gl_waitqueue_add (&lock->waiting_readers);
648 if (event != INVALID_HANDLE_VALUE)
651 LeaveCriticalSection (&lock->lock);
652 /* Wait until another thread signals this event. */
653 result = WaitForSingleObject (event, INFINITE);
654 if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
657 /* The thread which signalled the event already did the bookkeeping:
658 removed us from the waiting_readers, incremented lock->runcount. */
659 if (!(lock->runcount > 0))
665 /* Allocation failure. Weird. */
668 LeaveCriticalSection (&lock->lock);
670 EnterCriticalSection (&lock->lock);
672 while (!(lock->runcount + 1 > 0));
676 LeaveCriticalSection (&lock->lock);
680 glthread_rwlock_wrlock (gl_rwlock_t *lock)
682 if (!lock->guard.done)
684 if (InterlockedIncrement (&lock->guard.started) == 0)
685 /* This thread is the first one to need this lock. Initialize it. */
686 glthread_rwlock_init (lock);
688 /* Yield the CPU while waiting for another thread to finish
689 initializing this lock. */
690 while (!lock->guard.done)
693 EnterCriticalSection (&lock->lock);
694 /* Test whether no readers or writers are currently running. */
695 if (!(lock->runcount == 0))
697 /* This thread has to wait for a while. Enqueue it among the
699 HANDLE event = gl_waitqueue_add (&lock->waiting_writers);
700 if (event != INVALID_HANDLE_VALUE)
703 LeaveCriticalSection (&lock->lock);
704 /* Wait until another thread signals this event. */
705 result = WaitForSingleObject (event, INFINITE);
706 if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
709 /* The thread which signalled the event already did the bookkeeping:
710 removed us from the waiting_writers, set lock->runcount = -1. */
711 if (!(lock->runcount == -1))
717 /* Allocation failure. Weird. */
720 LeaveCriticalSection (&lock->lock);
722 EnterCriticalSection (&lock->lock);
724 while (!(lock->runcount == 0));
727 lock->runcount--; /* runcount becomes -1 */
728 LeaveCriticalSection (&lock->lock);
732 glthread_rwlock_unlock (gl_rwlock_t *lock)
734 if (!lock->guard.done)
736 EnterCriticalSection (&lock->lock);
737 if (lock->runcount < 0)
739 /* Drop a writer lock. */
740 if (!(lock->runcount == -1))
746 /* Drop a reader lock. */
747 if (!(lock->runcount > 0))
751 if (lock->runcount == 0)
753 /* POSIX recommends that "write locks shall take precedence over read
754 locks", to avoid "writer starvation". */
755 if (lock->waiting_writers.count > 0)
757 /* Wake up one of the waiting writers. */
759 gl_waitqueue_notify_first (&lock->waiting_writers);
763 /* Wake up all waiting readers. */
764 lock->runcount += lock->waiting_readers.count;
765 gl_waitqueue_notify_all (&lock->waiting_readers);
768 LeaveCriticalSection (&lock->lock);
772 glthread_rwlock_destroy (gl_rwlock_t *lock)
774 if (!lock->guard.done)
776 if (lock->runcount != 0)
778 DeleteCriticalSection (&lock->lock);
779 if (lock->waiting_readers.array != NULL)
780 free (lock->waiting_readers.array);
781 if (lock->waiting_writers.array != NULL)
782 free (lock->waiting_writers.array);
783 lock->guard.done = 0;
786 /* --------------------- gl_recursive_lock_t datatype --------------------- */
789 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
793 InitializeCriticalSection (&lock->lock);
794 lock->guard.done = 1;
798 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
800 if (!lock->guard.done)
802 if (InterlockedIncrement (&lock->guard.started) == 0)
803 /* This thread is the first one to need this lock. Initialize it. */
804 glthread_recursive_lock_init (lock);
806 /* Yield the CPU while waiting for another thread to finish
807 initializing this lock. */
808 while (!lock->guard.done)
812 DWORD self = GetCurrentThreadId ();
813 if (lock->owner != self)
815 EnterCriticalSection (&lock->lock);
818 if (++(lock->depth) == 0) /* wraparound? */
824 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
826 if (lock->owner != GetCurrentThreadId ())
828 if (lock->depth == 0)
830 if (--(lock->depth) == 0)
833 LeaveCriticalSection (&lock->lock);
838 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
840 if (lock->owner != 0)
842 DeleteCriticalSection (&lock->lock);
843 lock->guard.done = 0;
846 /* -------------------------- gl_once_t datatype -------------------------- */
849 glthread_once (gl_once_t *once_control, void (*initfunction) (void))
851 if (once_control->inited <= 0)
853 if (InterlockedIncrement (&once_control->started) == 0)
855 /* This thread is the first one to come to this once_control. */
856 InitializeCriticalSection (&once_control->lock);
857 EnterCriticalSection (&once_control->lock);
858 once_control->inited = 0;
860 once_control->inited = 1;
861 LeaveCriticalSection (&once_control->lock);
865 /* Undo last operation. */
866 InterlockedDecrement (&once_control->started);
867 /* Some other thread has already started the initialization.
868 Yield the CPU while waiting for the other thread to finish
869 initializing and taking the lock. */
870 while (once_control->inited < 0)
872 if (once_control->inited <= 0)
874 /* Take the lock. This blocks until the other thread has
875 finished calling the initfunction. */
876 EnterCriticalSection (&once_control->lock);
877 LeaveCriticalSection (&once_control->lock);
878 if (!(once_control->inited > 0))
887 /* ========================================================================= */