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 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,
27 /* ========================================================================= */
31 /* Use the POSIX threads library. */
33 # if PTHREAD_IN_USE_DETECTION_HARD
35 /* The function to be executed by a dummy thread. */
37 dummy_thread_func (void *arg
)
43 glthread_in_use (void)
46 static int result
; /* 1: linked with -lpthread, 0: only with libc */
52 if (pthread_create (&thread
, NULL
, dummy_thread_func
, NULL
) != 0)
53 /* Thread creation failed. */
57 /* Thread creation works. */
59 if (pthread_join (thread
, &retval
) != 0)
70 /* -------------------------- gl_lock_t datatype -------------------------- */
72 /* ------------------------- gl_rwlock_t datatype ------------------------- */
74 # if HAVE_PTHREAD_RWLOCK
76 # if !defined PTHREAD_RWLOCK_INITIALIZER
79 glthread_rwlock_init (gl_rwlock_t
*lock
)
81 if (pthread_rwlock_init (&lock
->rwlock
, NULL
) != 0)
83 lock
->initialized
= 1;
87 glthread_rwlock_rdlock (gl_rwlock_t
*lock
)
89 if (!lock
->initialized
)
91 if (pthread_mutex_lock (&lock
->guard
) != 0)
93 if (!lock
->initialized
)
94 glthread_rwlock_init (lock
);
95 if (pthread_mutex_unlock (&lock
->guard
) != 0)
98 if (pthread_rwlock_rdlock (&lock
->rwlock
) != 0)
103 glthread_rwlock_wrlock (gl_rwlock_t
*lock
)
105 if (!lock
->initialized
)
107 if (pthread_mutex_lock (&lock
->guard
) != 0)
109 if (!lock
->initialized
)
110 glthread_rwlock_init (lock
);
111 if (pthread_mutex_unlock (&lock
->guard
) != 0)
114 if (pthread_rwlock_wrlock (&lock
->rwlock
) != 0)
119 glthread_rwlock_unlock (gl_rwlock_t
*lock
)
121 if (!lock
->initialized
)
123 if (pthread_rwlock_unlock (&lock
->rwlock
) != 0)
128 glthread_rwlock_destroy (gl_rwlock_t
*lock
)
130 if (!lock
->initialized
)
132 if (pthread_rwlock_destroy (&lock
->rwlock
) != 0)
134 lock
->initialized
= 0;
142 glthread_rwlock_init (gl_rwlock_t
*lock
)
144 if (pthread_mutex_init (&lock
->lock
, NULL
) != 0)
146 if (pthread_cond_init (&lock
->waiting_readers
, NULL
) != 0)
148 if (pthread_cond_init (&lock
->waiting_writers
, NULL
) != 0)
150 lock
->waiting_writers_count
= 0;
155 glthread_rwlock_rdlock (gl_rwlock_t
*lock
)
157 if (pthread_mutex_lock (&lock
->lock
) != 0)
159 /* Test whether only readers are currently running, and whether the runcount
160 field will not overflow. */
161 /* POSIX says: "It is implementation-defined whether the calling thread
162 acquires the lock when a writer does not hold the lock and there are
163 writers blocked on the lock." Let's say, no: give the writers a higher
165 while (!(lock
->runcount
+ 1 > 0 && lock
->waiting_writers_count
== 0))
167 /* This thread has to wait for a while. Enqueue it among the
169 if (pthread_cond_wait (&lock
->waiting_readers
, &lock
->lock
) != 0)
173 if (pthread_mutex_unlock (&lock
->lock
) != 0)
178 glthread_rwlock_wrlock (gl_rwlock_t
*lock
)
180 if (pthread_mutex_lock (&lock
->lock
) != 0)
182 /* Test whether no readers or writers are currently running. */
183 while (!(lock
->runcount
== 0))
185 /* This thread has to wait for a while. Enqueue it among the
187 lock
->waiting_writers_count
++;
188 if (pthread_cond_wait (&lock
->waiting_writers
, &lock
->lock
) != 0)
190 lock
->waiting_writers_count
--;
192 lock
->runcount
--; /* runcount becomes -1 */
193 if (pthread_mutex_unlock (&lock
->lock
) != 0)
198 glthread_rwlock_unlock (gl_rwlock_t
*lock
)
200 if (pthread_mutex_lock (&lock
->lock
) != 0)
202 if (lock
->runcount
< 0)
204 /* Drop a writer lock. */
205 if (!(lock
->runcount
== -1))
211 /* Drop a reader lock. */
212 if (!(lock
->runcount
> 0))
216 if (lock
->runcount
== 0)
218 /* POSIX recommends that "write locks shall take precedence over read
219 locks", to avoid "writer starvation". */
220 if (lock
->waiting_writers_count
> 0)
222 /* Wake up one of the waiting writers. */
223 if (pthread_cond_signal (&lock
->waiting_writers
) != 0)
228 /* Wake up all waiting readers. */
229 if (pthread_cond_broadcast (&lock
->waiting_readers
) != 0)
233 if (pthread_mutex_unlock (&lock
->lock
) != 0)
238 glthread_rwlock_destroy (gl_rwlock_t
*lock
)
240 if (pthread_mutex_destroy (&lock
->lock
) != 0)
242 if (pthread_cond_destroy (&lock
->waiting_readers
) != 0)
244 if (pthread_cond_destroy (&lock
->waiting_writers
) != 0)
250 /* --------------------- gl_recursive_lock_t datatype --------------------- */
252 # if HAVE_PTHREAD_MUTEX_RECURSIVE
254 # if !(defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER || defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
257 glthread_recursive_lock_init (gl_recursive_lock_t
*lock
)
259 pthread_mutexattr_t attributes
;
261 if (pthread_mutexattr_init (&attributes
) != 0)
263 if (pthread_mutexattr_settype (&attributes
, PTHREAD_MUTEX_RECURSIVE
) != 0)
265 if (pthread_mutex_init (&lock
->recmutex
, &attributes
) != 0)
267 if (pthread_mutexattr_destroy (&attributes
) != 0)
269 lock
->initialized
= 1;
273 glthread_recursive_lock_lock (gl_recursive_lock_t
*lock
)
275 if (!lock
->initialized
)
277 if (pthread_mutex_lock (&lock
->guard
) != 0)
279 if (!lock
->initialized
)
280 glthread_recursive_lock_init (lock
);
281 if (pthread_mutex_unlock (&lock
->guard
) != 0)
284 if (pthread_mutex_lock (&lock
->recmutex
) != 0)
289 glthread_recursive_lock_unlock (gl_recursive_lock_t
*lock
)
291 if (!lock
->initialized
)
293 if (pthread_mutex_unlock (&lock
->recmutex
) != 0)
298 glthread_recursive_lock_destroy (gl_recursive_lock_t
*lock
)
300 if (!lock
->initialized
)
302 if (pthread_mutex_destroy (&lock
->recmutex
) != 0)
304 lock
->initialized
= 0;
312 glthread_recursive_lock_init (gl_recursive_lock_t
*lock
)
314 if (pthread_mutex_init (&lock
->mutex
, NULL
) != 0)
316 lock
->owner
= (pthread_t
) 0;
321 glthread_recursive_lock_lock (gl_recursive_lock_t
*lock
)
323 pthread_t self
= pthread_self ();
324 if (lock
->owner
!= self
)
326 if (pthread_mutex_lock (&lock
->mutex
) != 0)
330 if (++(lock
->depth
) == 0) /* wraparound? */
335 glthread_recursive_lock_unlock (gl_recursive_lock_t
*lock
)
337 if (lock
->owner
!= pthread_self ())
339 if (lock
->depth
== 0)
341 if (--(lock
->depth
) == 0)
343 lock
->owner
= (pthread_t
) 0;
344 if (pthread_mutex_unlock (&lock
->mutex
) != 0)
350 glthread_recursive_lock_destroy (gl_recursive_lock_t
*lock
)
352 if (lock
->owner
!= (pthread_t
) 0)
354 if (pthread_mutex_destroy (&lock
->mutex
) != 0)
360 /* -------------------------- gl_once_t datatype -------------------------- */
362 static const pthread_once_t fresh_once
= PTHREAD_ONCE_INIT
;
365 glthread_once_singlethreaded (pthread_once_t
*once_control
)
367 /* We don't know whether pthread_once_t is an integer type, a floating-point
368 type, a pointer type, or a structure type. */
369 char *firstbyte
= (char *)once_control
;
370 if (*firstbyte
== *(const char *)&fresh_once
)
372 /* First time use of once_control. Invert the first byte. */
373 *firstbyte
= ~ *(const char *)&fresh_once
;
382 /* ========================================================================= */
386 /* Use the GNU Pth threads library. */
388 /* -------------------------- gl_lock_t datatype -------------------------- */
390 /* ------------------------- gl_rwlock_t datatype ------------------------- */
392 /* --------------------- gl_recursive_lock_t datatype --------------------- */
394 /* -------------------------- gl_once_t datatype -------------------------- */
397 glthread_once_call (void *arg
)
399 void (**gl_once_temp_addr
) (void) = (void (**) (void)) arg
;
400 void (*initfunction
) (void) = *gl_once_temp_addr
;
405 glthread_once_singlethreaded (pth_once_t
*once_control
)
407 /* We know that pth_once_t is an integer type. */
408 if (*once_control
== PTH_ONCE_INIT
)
410 /* First time use of once_control. Invert the marker. */
411 *once_control
= ~ PTH_ONCE_INIT
;
420 /* ========================================================================= */
422 #if USE_SOLARIS_THREADS
424 /* Use the old Solaris threads library. */
426 /* -------------------------- gl_lock_t datatype -------------------------- */
428 /* ------------------------- gl_rwlock_t datatype ------------------------- */
430 /* --------------------- gl_recursive_lock_t datatype --------------------- */
433 glthread_recursive_lock_init (gl_recursive_lock_t
*lock
)
435 if (mutex_init (&lock
->mutex
, USYNC_THREAD
, NULL
) != 0)
437 lock
->owner
= (thread_t
) 0;
442 glthread_recursive_lock_lock (gl_recursive_lock_t
*lock
)
444 thread_t self
= thr_self ();
445 if (lock
->owner
!= self
)
447 if (mutex_lock (&lock
->mutex
) != 0)
451 if (++(lock
->depth
) == 0) /* wraparound? */
456 glthread_recursive_lock_unlock (gl_recursive_lock_t
*lock
)
458 if (lock
->owner
!= thr_self ())
460 if (lock
->depth
== 0)
462 if (--(lock
->depth
) == 0)
464 lock
->owner
= (thread_t
) 0;
465 if (mutex_unlock (&lock
->mutex
) != 0)
471 glthread_recursive_lock_destroy (gl_recursive_lock_t
*lock
)
473 if (lock
->owner
!= (thread_t
) 0)
475 if (mutex_destroy (&lock
->mutex
) != 0)
479 /* -------------------------- gl_once_t datatype -------------------------- */
482 glthread_once (gl_once_t
*once_control
, void (*initfunction
) (void))
484 if (!once_control
->inited
)
486 /* Use the mutex to guarantee that if another thread is already calling
487 the initfunction, this thread waits until it's finished. */
488 if (mutex_lock (&once_control
->mutex
) != 0)
490 if (!once_control
->inited
)
492 once_control
->inited
= 1;
495 if (mutex_unlock (&once_control
->mutex
) != 0)
501 glthread_once_singlethreaded (gl_once_t
*once_control
)
503 /* We know that gl_once_t contains an integer type. */
504 if (!once_control
->inited
)
506 /* First time use of once_control. Invert the marker. */
507 once_control
->inited
= ~ 0;
516 /* ========================================================================= */
518 #if USE_WIN32_THREADS
520 /* -------------------------- gl_lock_t datatype -------------------------- */
523 glthread_lock_init (gl_lock_t
*lock
)
525 InitializeCriticalSection (&lock
->lock
);
526 lock
->guard
.done
= 1;
530 glthread_lock_lock (gl_lock_t
*lock
)
532 if (!lock
->guard
.done
)
534 if (InterlockedIncrement (&lock
->guard
.started
) == 0)
535 /* This thread is the first one to need this lock. Initialize it. */
536 glthread_lock_init (lock
);
538 /* Yield the CPU while waiting for another thread to finish
539 initializing this lock. */
540 while (!lock
->guard
.done
)
543 EnterCriticalSection (&lock
->lock
);
547 glthread_lock_unlock (gl_lock_t
*lock
)
549 if (!lock
->guard
.done
)
551 LeaveCriticalSection (&lock
->lock
);
555 glthread_lock_destroy (gl_lock_t
*lock
)
557 if (!lock
->guard
.done
)
559 DeleteCriticalSection (&lock
->lock
);
560 lock
->guard
.done
= 0;
563 /* ------------------------- gl_rwlock_t datatype ------------------------- */
566 gl_waitqueue_init (gl_waitqueue_t
*wq
)
574 /* Enqueues the current thread, represented by an event, in a wait queue.
575 Returns INVALID_HANDLE_VALUE if an allocation failure occurs. */
577 gl_waitqueue_add (gl_waitqueue_t
*wq
)
582 if (wq
->count
== wq
->alloc
)
584 unsigned int new_alloc
= 2 * wq
->alloc
+ 1;
586 (HANDLE
*) realloc (wq
->array
, new_alloc
* sizeof (HANDLE
));
587 if (new_array
== NULL
)
588 /* No more memory. */
589 return INVALID_HANDLE_VALUE
;
590 /* Now is a good opportunity to rotate the array so that its contents
591 starts at offset 0. */
594 unsigned int old_count
= wq
->count
;
595 unsigned int old_alloc
= wq
->alloc
;
596 unsigned int old_offset
= wq
->offset
;
598 if (old_offset
+ old_count
> old_alloc
)
600 unsigned int limit
= old_offset
+ old_count
- old_alloc
;
601 for (i
= 0; i
< limit
; i
++)
602 new_array
[old_alloc
+ i
] = new_array
[i
];
604 for (i
= 0; i
< old_count
; i
++)
605 new_array
[i
] = new_array
[old_offset
+ i
];
608 wq
->array
= new_array
;
609 wq
->alloc
= new_alloc
;
611 event
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
612 if (event
== INVALID_HANDLE_VALUE
)
613 /* No way to allocate an event. */
614 return INVALID_HANDLE_VALUE
;
615 index
= wq
->offset
+ wq
->count
;
616 if (index
>= wq
->alloc
)
618 wq
->array
[index
] = event
;
623 /* Notifies the first thread from a wait queue and dequeues it. */
625 gl_waitqueue_notify_first (gl_waitqueue_t
*wq
)
627 SetEvent (wq
->array
[wq
->offset
+ 0]);
630 if (wq
->count
== 0 || wq
->offset
== wq
->alloc
)
634 /* Notifies all threads from a wait queue and dequeues them all. */
636 gl_waitqueue_notify_all (gl_waitqueue_t
*wq
)
640 for (i
= 0; i
< wq
->count
; i
++)
642 unsigned int index
= wq
->offset
+ i
;
643 if (index
>= wq
->alloc
)
645 SetEvent (wq
->array
[index
]);
652 glthread_rwlock_init (gl_rwlock_t
*lock
)
654 InitializeCriticalSection (&lock
->lock
);
655 gl_waitqueue_init (&lock
->waiting_readers
);
656 gl_waitqueue_init (&lock
->waiting_writers
);
658 lock
->guard
.done
= 1;
662 glthread_rwlock_rdlock (gl_rwlock_t
*lock
)
664 if (!lock
->guard
.done
)
666 if (InterlockedIncrement (&lock
->guard
.started
) == 0)
667 /* This thread is the first one to need this lock. Initialize it. */
668 glthread_rwlock_init (lock
);
670 /* Yield the CPU while waiting for another thread to finish
671 initializing this lock. */
672 while (!lock
->guard
.done
)
675 EnterCriticalSection (&lock
->lock
);
676 /* Test whether only readers are currently running, and whether the runcount
677 field will not overflow. */
678 if (!(lock
->runcount
+ 1 > 0))
680 /* This thread has to wait for a while. Enqueue it among the
682 HANDLE event
= gl_waitqueue_add (&lock
->waiting_readers
);
683 if (event
!= INVALID_HANDLE_VALUE
)
686 LeaveCriticalSection (&lock
->lock
);
687 /* Wait until another thread signals this event. */
688 result
= WaitForSingleObject (event
, INFINITE
);
689 if (result
== WAIT_FAILED
|| result
== WAIT_TIMEOUT
)
692 /* The thread which signalled the event already did the bookkeeping:
693 removed us from the waiting_readers, incremented lock->runcount. */
694 if (!(lock
->runcount
> 0))
700 /* Allocation failure. Weird. */
703 LeaveCriticalSection (&lock
->lock
);
705 EnterCriticalSection (&lock
->lock
);
707 while (!(lock
->runcount
+ 1 > 0));
711 LeaveCriticalSection (&lock
->lock
);
715 glthread_rwlock_wrlock (gl_rwlock_t
*lock
)
717 if (!lock
->guard
.done
)
719 if (InterlockedIncrement (&lock
->guard
.started
) == 0)
720 /* This thread is the first one to need this lock. Initialize it. */
721 glthread_rwlock_init (lock
);
723 /* Yield the CPU while waiting for another thread to finish
724 initializing this lock. */
725 while (!lock
->guard
.done
)
728 EnterCriticalSection (&lock
->lock
);
729 /* Test whether no readers or writers are currently running. */
730 if (!(lock
->runcount
== 0))
732 /* This thread has to wait for a while. Enqueue it among the
734 HANDLE event
= gl_waitqueue_add (&lock
->waiting_writers
);
735 if (event
!= INVALID_HANDLE_VALUE
)
738 LeaveCriticalSection (&lock
->lock
);
739 /* Wait until another thread signals this event. */
740 result
= WaitForSingleObject (event
, INFINITE
);
741 if (result
== WAIT_FAILED
|| result
== WAIT_TIMEOUT
)
744 /* The thread which signalled the event already did the bookkeeping:
745 removed us from the waiting_writers, set lock->runcount = -1. */
746 if (!(lock
->runcount
== -1))
752 /* Allocation failure. Weird. */
755 LeaveCriticalSection (&lock
->lock
);
757 EnterCriticalSection (&lock
->lock
);
759 while (!(lock
->runcount
== 0));
762 lock
->runcount
--; /* runcount becomes -1 */
763 LeaveCriticalSection (&lock
->lock
);
767 glthread_rwlock_unlock (gl_rwlock_t
*lock
)
769 if (!lock
->guard
.done
)
771 EnterCriticalSection (&lock
->lock
);
772 if (lock
->runcount
< 0)
774 /* Drop a writer lock. */
775 if (!(lock
->runcount
== -1))
781 /* Drop a reader lock. */
782 if (!(lock
->runcount
> 0))
786 if (lock
->runcount
== 0)
788 /* POSIX recommends that "write locks shall take precedence over read
789 locks", to avoid "writer starvation". */
790 if (lock
->waiting_writers
.count
> 0)
792 /* Wake up one of the waiting writers. */
794 gl_waitqueue_notify_first (&lock
->waiting_writers
);
798 /* Wake up all waiting readers. */
799 lock
->runcount
+= lock
->waiting_readers
.count
;
800 gl_waitqueue_notify_all (&lock
->waiting_readers
);
803 LeaveCriticalSection (&lock
->lock
);
807 glthread_rwlock_destroy (gl_rwlock_t
*lock
)
809 if (!lock
->guard
.done
)
811 if (lock
->runcount
!= 0)
813 DeleteCriticalSection (&lock
->lock
);
814 if (lock
->waiting_readers
.array
!= NULL
)
815 free (lock
->waiting_readers
.array
);
816 if (lock
->waiting_writers
.array
!= NULL
)
817 free (lock
->waiting_writers
.array
);
818 lock
->guard
.done
= 0;
821 /* --------------------- gl_recursive_lock_t datatype --------------------- */
824 glthread_recursive_lock_init (gl_recursive_lock_t
*lock
)
828 InitializeCriticalSection (&lock
->lock
);
829 lock
->guard
.done
= 1;
833 glthread_recursive_lock_lock (gl_recursive_lock_t
*lock
)
835 if (!lock
->guard
.done
)
837 if (InterlockedIncrement (&lock
->guard
.started
) == 0)
838 /* This thread is the first one to need this lock. Initialize it. */
839 glthread_recursive_lock_init (lock
);
841 /* Yield the CPU while waiting for another thread to finish
842 initializing this lock. */
843 while (!lock
->guard
.done
)
847 DWORD self
= GetCurrentThreadId ();
848 if (lock
->owner
!= self
)
850 EnterCriticalSection (&lock
->lock
);
853 if (++(lock
->depth
) == 0) /* wraparound? */
859 glthread_recursive_lock_unlock (gl_recursive_lock_t
*lock
)
861 if (lock
->owner
!= GetCurrentThreadId ())
863 if (lock
->depth
== 0)
865 if (--(lock
->depth
) == 0)
868 LeaveCriticalSection (&lock
->lock
);
873 glthread_recursive_lock_destroy (gl_recursive_lock_t
*lock
)
875 if (lock
->owner
!= 0)
877 DeleteCriticalSection (&lock
->lock
);
878 lock
->guard
.done
= 0;
881 /* -------------------------- gl_once_t datatype -------------------------- */
884 glthread_once (gl_once_t
*once_control
, void (*initfunction
) (void))
886 if (once_control
->inited
<= 0)
888 if (InterlockedIncrement (&once_control
->started
) == 0)
890 /* This thread is the first one to come to this once_control. */
891 InitializeCriticalSection (&once_control
->lock
);
892 EnterCriticalSection (&once_control
->lock
);
893 once_control
->inited
= 0;
895 once_control
->inited
= 1;
896 LeaveCriticalSection (&once_control
->lock
);
900 /* Undo last operation. */
901 InterlockedDecrement (&once_control
->started
);
902 /* Some other thread has already started the initialization.
903 Yield the CPU while waiting for the other thread to finish
904 initializing and taking the lock. */
905 while (once_control
->inited
< 0)
907 if (once_control
->inited
<= 0)
909 /* Take the lock. This blocks until the other thread has
910 finished calling the initfunction. */
911 EnterCriticalSection (&once_control
->lock
);
912 LeaveCriticalSection (&once_control
->lock
);
913 if (!(once_control
->inited
> 0))
922 /* ========================================================================= */