New gnulib module 'lock'.
[pspp] / lib / lock.c
1 /* Locking in multithreaded situations.
2    Copyright (C) 2005 Free Software Foundation, Inc.
3
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)
7    any later version.
8
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.
13
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,
17    USA.  */
18
19 /* Written by Bruno Haible <bruno@clisp.org>, 2005.
20    Based on GCC's gthr-posix.h, gthr-posix95.h, gthr-solaris.h,
21    gthr-win32.h.  */
22
23 #ifdef HAVE_CONFIG_H
24 # include <config.h>
25 #endif
26
27 #include "lock.h"
28
29 /* ========================================================================= */
30
31 #if USE_POSIX_THREADS
32
33 /* Use the POSIX threads library.  */
34
35 /* -------------------------- gl_lock_t datatype -------------------------- */
36
37 /* ------------------------- gl_rwlock_t datatype ------------------------- */
38
39 # if HAVE_PTHREAD_RWLOCK
40
41 #  if !defined PTHREAD_RWLOCK_INITIALIZER
42
43 void
44 glthread_rwlock_init (gl_rwlock_t *lock)
45 {
46   if (pthread_rwlock_init (&lock->rwlock, NULL) != 0)
47     abort ();
48   lock->initialized = 1;
49 }
50
51 void
52 glthread_rwlock_rdlock (gl_rwlock_t *lock)
53 {
54   if (!lock->initialized)
55     {
56       if (pthread_mutex_lock (&lock->guard) != 0)
57         abort ();
58       if (!lock->initialized)
59         glthread_rwlock_init (lock);
60       if (pthread_mutex_unlock (&lock->guard) != 0)
61         abort ();
62     }
63   if (pthread_rwlock_rdlock (&lock->rwlock) != 0)
64     abort ();
65 }
66
67 void
68 glthread_rwlock_wrlock (gl_rwlock_t *lock)
69 {
70   if (!lock->initialized)
71     {
72       if (pthread_mutex_lock (&lock->guard) != 0)
73         abort ();
74       if (!lock->initialized)
75         glthread_rwlock_init (lock);
76       if (pthread_mutex_unlock (&lock->guard) != 0)
77         abort ();
78     }
79   if (pthread_rwlock_wrlock (&lock->rwlock) != 0)
80     abort ();
81 }
82
83 void
84 glthread_rwlock_unlock (gl_rwlock_t *lock)
85 {
86   if (!lock->initialized)
87     abort ();
88   if (pthread_rwlock_unlock (&lock->rwlock) != 0)
89     abort ();
90 }
91
92 void
93 glthread_rwlock_destroy (gl_rwlock_t *lock)
94 {
95   if (!lock->initialized)
96     abort ();
97   if (pthread_rwlock_destroy (&lock->rwlock) != 0)
98     abort ();
99   lock->initialized = 0;
100 }
101
102 #  endif
103
104 # else
105
106 void
107 glthread_rwlock_init (gl_rwlock_t *lock)
108 {
109   if (pthread_mutex_init (&lock->lock, NULL) != 0)
110     abort ();
111   if (pthread_cond_init (&lock->waiting_readers, NULL) != 0)
112     abort ();
113   if (pthread_cond_init (&lock->waiting_writers, NULL) != 0)
114     abort ();
115   lock->waiting_writers_count = 0;
116   lock->runcount = 0;
117 }
118
119 void
120 glthread_rwlock_rdlock (gl_rwlock_t *lock)
121 {
122   if (pthread_mutex_lock (&lock->lock) != 0)
123     abort ();
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
129      priority.  */
130   while (!(lock->runcount + 1 > 0 && lock->waiting_writers_count == 0))
131     {
132       /* This thread has to wait for a while.  Enqueue it among the
133          waiting_readers.  */
134       if (pthread_cond_wait (&lock->waiting_readers, &lock->lock) != 0)
135         abort ();
136     }
137   lock->runcount++;
138   if (pthread_mutex_unlock (&lock->lock) != 0)
139     abort ();
140 }
141
142 void
143 glthread_rwlock_wrlock (gl_rwlock_t *lock)
144 {
145   if (pthread_mutex_lock (&lock->lock) != 0)
146     abort ();
147   /* Test whether no readers or writers are currently running.  */
148   while (!(lock->runcount == 0))
149     {
150       /* This thread has to wait for a while.  Enqueue it among the
151          waiting_writers.  */
152       lock->waiting_writers_count++;
153       if (pthread_cond_wait (&lock->waiting_writers, &lock->lock) != 0)
154         abort ();
155       lock->waiting_writers_count--;
156     }
157   lock->runcount--; /* runcount becomes -1 */
158   if (pthread_mutex_unlock (&lock->lock) != 0)
159     abort ();
160 }
161
162 void
163 glthread_rwlock_unlock (gl_rwlock_t *lock)
164 {
165   if (pthread_mutex_lock (&lock->lock) != 0)
166     abort ();
167   if (lock->runcount < 0)
168     {
169       /* Drop a writer lock.  */
170       if (!(lock->runcount == -1))
171         abort ();
172       lock->runcount = 0;
173     }
174   else
175     {
176       /* Drop a reader lock.  */
177       if (!(lock->runcount > 0))
178         abort ();
179       lock->runcount--;
180     }
181   if (lock->runcount == 0)
182     {
183       /* POSIX recommends that "write locks shall take precedence over read
184          locks", to avoid "writer starvation".  */
185       if (lock->waiting_writers_count > 0)
186         {
187           /* Wake up one of the waiting writers.  */
188           if (pthread_cond_signal (&lock->waiting_writers) != 0)
189             abort ();
190         }
191       else
192         {
193           /* Wake up all waiting readers.  */
194           if (pthread_cond_broadcast (&lock->waiting_readers) != 0)
195             abort ();
196         }
197     }
198   if (pthread_mutex_unlock (&lock->lock) != 0)
199     abort ();
200 }
201
202 void
203 glthread_rwlock_destroy (gl_rwlock_t *lock)
204 {
205   if (pthread_mutex_destroy (&lock->lock) != 0)
206     abort ();
207   if (pthread_cond_destroy (&lock->waiting_readers) != 0)
208     abort ();
209   if (pthread_cond_destroy (&lock->waiting_writers) != 0)
210     abort ();
211 }
212
213 # endif
214
215 /* --------------------- gl_recursive_lock_t datatype --------------------- */
216
217 # if HAVE_PTHREAD_MUTEX_RECURSIVE
218
219 #  if !(defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER || defined PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
220
221 void
222 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
223 {
224   pthread_mutexattr_t attributes;
225
226   if (pthread_mutexattr_init (&attributes) != 0)
227     abort ();
228   if (pthread_mutexattr_settype (&attributes, PTHREAD_MUTEX_RECURSIVE) != 0)
229     abort ();
230   if (pthread_mutex_init (&lock->recmutex, &attributes) != 0)
231     abort ();
232   if (pthread_mutexattr_destroy (&attributes) != 0)
233     abort ();
234   lock->initialized = 1;
235 }
236
237 void
238 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
239 {
240   if (!lock->initialized)
241     {
242       if (pthread_mutex_lock (&lock->guard) != 0)
243         abort ();
244       if (!lock->initialized)
245         glthread_recursive_lock_init (lock);
246       if (pthread_mutex_unlock (&lock->guard) != 0)
247         abort ();
248     }
249   if (pthread_mutex_lock (&lock->recmutex) != 0)
250     abort ();
251 }
252
253 void
254 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
255 {
256   if (!lock->initialized)
257     abort ();
258   if (pthread_mutex_unlock (&lock->recmutex) != 0)
259     abort ();
260 }
261
262 void
263 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
264 {
265   if (!lock->initialized)
266     abort ();
267   if (pthread_mutex_destroy (&lock->recmutex) != 0)
268     abort ();
269   lock->initialized = 0;
270 }
271
272 #  endif
273
274 # else
275
276 void
277 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
278 {
279   if (pthread_mutex_init (&lock->mutex, NULL) != 0)
280     abort ();
281   lock->owner = (pthread_t) 0;
282   lock->depth = 0;
283 }
284
285 void
286 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
287 {
288   pthread_t self = pthread_self ();
289   if (lock->owner != self)
290     {
291       if (pthread_mutex_lock (&lock->mutex) != 0)
292         abort ();
293       lock->owner = self;
294     }
295   if (++(lock->depth) == 0) /* wraparound? */
296     abort ();
297 }
298
299 void
300 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
301 {
302   if (lock->owner != pthread_self ())
303     abort ();
304   if (lock->depth == 0)
305     abort ();
306   if (--(lock->depth) == 0)
307     {
308       lock->owner = (pthread_t) 0;
309       if (pthread_mutex_unlock (&lock->mutex) != 0)
310         abort ();
311     }
312 }
313
314 void
315 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
316 {
317   if (lock->owner != (pthread_t) 0)
318     abort ();
319   if (pthread_mutex_destroy (&lock->mutex) != 0)
320     abort ();
321 }
322
323 # endif
324
325 #endif
326
327 /* ========================================================================= */
328
329 #if USE_PTH_THREADS
330
331 /* Use the GNU Pth threads library.  */
332
333 /* -------------------------- gl_lock_t datatype -------------------------- */
334
335 /* ------------------------- gl_rwlock_t datatype ------------------------- */
336
337 /* --------------------- gl_recursive_lock_t datatype --------------------- */
338
339 #endif
340
341 /* ========================================================================= */
342
343 #if USE_SOLARIS_THREADS
344
345 /* Use the old Solaris threads library.  */
346
347 /* -------------------------- gl_lock_t datatype -------------------------- */
348
349 /* ------------------------- gl_rwlock_t datatype ------------------------- */
350
351 /* --------------------- gl_recursive_lock_t datatype --------------------- */
352
353 void
354 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
355 {
356   if (mutex_init (&lock->mutex, USYNC_THREAD, NULL) != 0)
357     abort ();
358   lock->owner = (thread_t) 0;
359   lock->depth = 0;
360 }
361
362 void
363 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
364 {
365   thread_t self = thr_self ();
366   if (lock->owner != self)
367     {
368       if (mutex_lock (&lock->mutex) != 0)
369         abort ();
370       lock->owner = self;
371     }
372   if (++(lock->depth) == 0) /* wraparound? */
373     abort ();
374 }
375
376 void
377 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
378 {
379   if (lock->owner != thr_self ())
380     abort ();
381   if (lock->depth == 0)
382     abort ();
383   if (--(lock->depth) == 0)
384     {
385       lock->owner = (thread_t) 0;
386       if (mutex_unlock (&lock->mutex) != 0)
387         abort ();
388     }
389 }
390
391 void
392 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
393 {
394   if (lock->owner != (thread_t) 0)
395     abort ();
396   if (mutex_destroy (&lock->mutex) != 0)
397     abort ();
398 }
399
400 #endif
401
402 /* ========================================================================= */
403
404 #if USE_WIN32_THREADS
405
406 /* -------------------------- gl_lock_t datatype -------------------------- */
407
408 void
409 glthread_lock_init (gl_lock_t *lock)
410 {
411   InitializeCriticalSection (&lock->lock);
412   lock->guard.done = 1;
413 }
414
415 void
416 glthread_lock_lock (gl_lock_t *lock)
417 {
418   if (!lock->guard.done)
419     {
420       if (InterlockedIncrement (&lock->guard.started) == 0)
421         /* This thread is the first one to need this lock.  Initialize it.  */
422         glthread_lock_init (lock);
423       else
424         /* Yield the CPU while waiting for another thread to finish
425            initializing this lock.  */
426         while (!lock->guard.done)
427           Sleep (0);
428     }
429   EnterCriticalSection (&lock->lock);
430 }
431
432 void
433 glthread_lock_unlock (gl_lock_t *lock)
434 {
435   if (!lock->guard.done)
436     abort ();
437   LeaveCriticalSection (&lock->lock);
438 }
439
440 void
441 glthread_lock_destroy (gl_lock_t *lock)
442 {
443   if (!lock->guard.done)
444     abort ();
445   DeleteCriticalSection (&lock->lock);
446   lock->guard.done = 0;
447 }
448
449 /* ------------------------- gl_rwlock_t datatype ------------------------- */
450
451 static inline void
452 gl_waitqueue_init (gl_waitqueue_t *wq)
453 {
454   wq->array = NULL;
455   wq->count = 0;
456   wq->alloc = 0;
457   wq->offset = 0;
458 }
459
460 /* Enqueues the current thread, represented by an event, in a wait queue.
461    Returns INVALID_HANDLE_VALUE if an allocation failure occurs.  */
462 static HANDLE
463 gl_waitqueue_add (gl_waitqueue_t *wq)
464 {
465   HANDLE event;
466   unsigned int index;
467
468   if (wq->count == wq->alloc)
469     {
470       unsigned int new_alloc = 2 * wq->alloc + 1;
471       HANDLE *new_array =
472         (HANDLE *) realloc (wq->array, new_alloc * sizeof (HANDLE));
473       if (new_array == NULL)
474         /* No more memory.  */
475         return INVALID_HANDLE_VALUE;
476       /* Now is a good opportunity to rotate the array so that its contents
477          starts at offset 0.  */
478       if (wq->offset > 0)
479         {
480           unsigned int old_count = wq->count;
481           unsigned int old_alloc = wq->alloc;
482           unsigned int old_offset = wq->offset;
483           unsigned int i;
484           if (old_offset + old_count > old_alloc)
485             {
486               unsigned int limit = old_offset + old_count - old_alloc;
487               for (i = 0; i < limit; i++)
488                 new_array[old_alloc + i] = new_array[i];
489             }
490           for (i = 0; i < old_count; i++)
491             new_array[i] = new_array[old_offset + i];
492           wq->offset = 0;
493         }
494       wq->array = new_array;
495       wq->alloc = new_alloc;
496     }
497   event = CreateEvent (NULL, TRUE, FALSE, NULL);
498   if (event == INVALID_HANDLE_VALUE)
499     /* No way to allocate an event.  */
500     return INVALID_HANDLE_VALUE;
501   index = wq->offset + wq->count;
502   if (index >= wq->alloc)
503     index -= wq->alloc;
504   wq->array[index] = event;
505   wq->count++;
506   return event;
507 }
508
509 /* Notifies the first thread from a wait queue and dequeues it.  */
510 static inline void
511 gl_waitqueue_notify_first (gl_waitqueue_t *wq)
512 {
513   SetEvent (wq->array[wq->offset + 0]);
514   wq->offset++;
515   wq->count--;
516   if (wq->count == 0 || wq->offset == wq->alloc)
517     wq->offset = 0;
518 }
519
520 /* Notifies all threads from a wait queue and dequeues them all.  */
521 static inline void
522 gl_waitqueue_notify_all (gl_waitqueue_t *wq)
523 {
524   unsigned int i;
525
526   for (i = 0; i < wq->count; i++)
527     {
528       unsigned int index = wq->offset + i;
529       if (index >= wq->alloc)
530         index -= wq->alloc;
531       SetEvent (wq->array[index]);
532     }
533   wq->count = 0;
534   wq->offset = 0;
535 }
536
537 void
538 glthread_rwlock_init (gl_rwlock_t *lock)
539 {
540   InitializeCriticalSection (&lock->lock);
541   gl_waitqueue_init (&lock->waiting_readers);
542   gl_waitqueue_init (&lock->waiting_writers);
543   lock->runcount = 0;
544   lock->guard.done = 1;
545 }
546
547 void
548 glthread_rwlock_rdlock (gl_rwlock_t *lock)
549 {
550   if (!lock->guard.done)
551     {
552       if (InterlockedIncrement (&lock->guard.started) == 0)
553         /* This thread is the first one to need this lock.  Initialize it.  */
554         glthread_rwlock_init (lock);
555       else
556         /* Yield the CPU while waiting for another thread to finish
557            initializing this lock.  */
558         while (!lock->guard.done)
559           Sleep (0);
560     }
561   EnterCriticalSection (&lock->lock);
562   /* Test whether only readers are currently running, and whether the runcount
563      field will not overflow.  */
564   if (!(lock->runcount + 1 > 0))
565     {
566       /* This thread has to wait for a while.  Enqueue it among the
567          waiting_readers.  */
568       HANDLE event = gl_waitqueue_add (&lock->waiting_readers);
569       if (event != INVALID_HANDLE_VALUE)
570         {
571           DWORD result;
572           LeaveCriticalSection (&lock->lock);
573           /* Wait until another thread signals this event.  */
574           result = WaitForSingleObject (event, INFINITE);
575           if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
576             abort ();
577           CloseHandle (event);
578           /* The thread which signalled the event already did the bookkeeping:
579              removed us from the waiting_readers, incremented lock->runcount.  */
580           if (!(lock->runcount > 0))
581             abort ();
582           return;
583         }
584       else
585         {
586           /* Allocation failure.  Weird.  */
587           do
588             {
589               LeaveCriticalSection (&lock->lock);
590               Sleep (1);
591               EnterCriticalSection (&lock->lock);
592             }
593           while (!(lock->runcount + 1 > 0));
594         }
595     }
596   lock->runcount++;
597   LeaveCriticalSection (&lock->lock);
598 }
599
600 void
601 glthread_rwlock_wrlock (gl_rwlock_t *lock)
602 {
603   if (!lock->guard.done)
604     {
605       if (InterlockedIncrement (&lock->guard.started) == 0)
606         /* This thread is the first one to need this lock.  Initialize it.  */
607         glthread_rwlock_init (lock);
608       else
609         /* Yield the CPU while waiting for another thread to finish
610            initializing this lock.  */
611         while (!lock->guard.done)
612           Sleep (0);
613     }
614   EnterCriticalSection (&lock->lock);
615   /* Test whether no readers or writers are currently running.  */
616   if (!(lock->runcount == 0))
617     {
618       /* This thread has to wait for a while.  Enqueue it among the
619          waiting_writers.  */
620       HANDLE event = gl_waitqueue_add (&lock->waiting_writers);
621       if (event != INVALID_HANDLE_VALUE)
622         {
623           DWORD result;
624           LeaveCriticalSection (&lock->lock);
625           /* Wait until another thread signals this event.  */
626           result = WaitForSingleObject (event, INFINITE);
627           if (result == WAIT_FAILED || result == WAIT_TIMEOUT)
628             abort ();
629           CloseHandle (event);
630           /* The thread which signalled the event already did the bookkeeping:
631              removed us from the waiting_writers, set lock->runcount = -1.  */
632           if (!(lock->runcount == -1))
633             abort ();
634           return;
635         }
636       else
637         {
638           /* Allocation failure.  Weird.  */
639           do
640             {
641               LeaveCriticalSection (&lock->lock);
642               Sleep (1);
643               EnterCriticalSection (&lock->lock);
644             }
645           while (!(lock->runcount == 0));
646         }
647     }
648   lock->runcount--; /* runcount becomes -1 */
649   LeaveCriticalSection (&lock->lock);
650 }
651
652 void
653 glthread_rwlock_unlock (gl_rwlock_t *lock)
654 {
655   if (!lock->guard.done)
656     abort ();
657   EnterCriticalSection (&lock->lock);
658   if (lock->runcount < 0)
659     {
660       /* Drop a writer lock.  */
661       if (!(lock->runcount == -1))
662         abort ();
663       lock->runcount = 0;
664     }
665   else
666     {
667       /* Drop a reader lock.  */
668       if (!(lock->runcount > 0))
669         abort ();
670       lock->runcount--;
671     }
672   if (lock->runcount == 0)
673     {
674       /* POSIX recommends that "write locks shall take precedence over read
675          locks", to avoid "writer starvation".  */
676       if (lock->waiting_writers.count > 0)
677         {
678           /* Wake up one of the waiting writers.  */
679           lock->runcount--;
680           gl_waitqueue_notify_first (&lock->waiting_writers);
681         }
682       else
683         {
684           /* Wake up all waiting readers.  */
685           lock->runcount += lock->waiting_readers.count;
686           gl_waitqueue_notify_all (&lock->waiting_readers);
687         }
688     }
689   LeaveCriticalSection (&lock->lock);
690 }
691
692 void
693 glthread_rwlock_destroy (gl_rwlock_t *lock)
694 {
695   if (!lock->guard.done)
696     abort ();
697   if (lock->runcount != 0)
698     abort ();
699   DeleteCriticalSection (&lock->lock);
700   if (lock->waiting_readers.array != NULL)
701     free (lock->waiting_readers.array);
702   if (lock->waiting_writers.array != NULL)
703     free (lock->waiting_writers.array);
704   lock->guard.done = 0;
705 }
706
707 /* --------------------- gl_recursive_lock_t datatype --------------------- */
708
709 void
710 glthread_recursive_lock_init (gl_recursive_lock_t *lock)
711 {
712   lock->owner = 0;
713   lock->depth = 0;
714   InitializeCriticalSection (&lock->lock);
715   lock->guard.done = 1;
716 }
717
718 void
719 glthread_recursive_lock_lock (gl_recursive_lock_t *lock)
720 {
721   if (!lock->guard.done)
722     {
723       if (InterlockedIncrement (&lock->guard.started) == 0)
724         /* This thread is the first one to need this lock.  Initialize it.  */
725         glthread_recursive_lock_init (lock);
726       else
727         /* Yield the CPU while waiting for another thread to finish
728            initializing this lock.  */
729         while (!lock->guard.done)
730           Sleep (0);
731     }
732   {
733     DWORD self = GetCurrentThreadId ();
734     if (lock->owner != self)
735       {
736         EnterCriticalSection (&lock->lock);
737         lock->owner = self;
738       }
739     if (++(lock->depth) == 0) /* wraparound? */
740       abort ();
741   }
742 }
743
744 void
745 glthread_recursive_lock_unlock (gl_recursive_lock_t *lock)
746 {
747   if (lock->owner != GetCurrentThreadId ())
748     abort ();
749   if (lock->depth == 0)
750     abort ();
751   if (--(lock->depth) == 0)
752     {
753       lock->owner = 0;
754       LeaveCriticalSection (&lock->lock);
755     }
756 }
757
758 void
759 glthread_recursive_lock_destroy (gl_recursive_lock_t *lock)
760 {
761   if (lock->owner != 0)
762     abort ();
763   DeleteCriticalSection (&lock->lock);
764   lock->guard.done = 0;
765 }
766
767 #endif
768
769 /* ========================================================================= */