OSDN Git Service

2001-06-27 Phil Edwards <pme@sources.redhat.com>
[pf3gnuchains/gcc-fork.git] / libstdc++-v3 / include / bits / stl_threads.h
1 // Threading support -*- C++ -*-
2
3 // Copyright (C) 2001 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library.  This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 2, or (at your option)
9 // any later version.
10
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15
16 // You should have received a copy of the GNU General Public License along
17 // with this library; see the file COPYING.  If not, write to the Free
18 // Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
19 // USA.
20
21 // As a special exception, you may use this file as part of a free software
22 // library without restriction.  Specifically, if other files instantiate
23 // templates or use macros or inline functions from this file, or you compile
24 // this file and link it with other files to produce an executable, this
25 // file does not by itself cause the resulting executable to be covered by
26 // the GNU General Public License.  This exception does not however
27 // invalidate any other reasons why the executable file might be covered by
28 // the GNU General Public License.
29
30 /*
31  * Copyright (c) 1997-1999
32  * Silicon Graphics Computer Systems, Inc.
33  *
34  * Permission to use, copy, modify, distribute and sell this software
35  * and its documentation for any purpose is hereby granted without fee,
36  * provided that the above copyright notice appear in all copies and
37  * that both that copyright notice and this permission notice appear
38  * in supporting documentation.  Silicon Graphics makes no
39  * representations about the suitability of this software for any
40  * purpose.  It is provided "as is" without express or implied warranty.
41  */
42
43 // WARNING: This is an internal header file, included by other C++
44 // standard library headers.  You should not attempt to use this header
45 // file directly.
46 // Stl_config.h should be included before this file.
47
48 #ifndef __SGI_STL_INTERNAL_THREADS_H
49 #define __SGI_STL_INTERNAL_THREADS_H
50
51 // Supported threading models are native SGI, pthreads, uithreads
52 // (similar to pthreads, but based on an earlier draft of the Posix
53 // threads standard), and Win32 threads.  Uithread support by Jochen
54 // Schlick, 1999.
55
56 // GCC extension begin
57 // In order to present a stable threading configuration, in all cases,
58 // gcc looks for it's own abstraction layer before all others.  All
59 // modifications to this file are marked to allow easier importation of
60 // STL upgrades.
61 #if defined(__STL_GTHREADS)
62 #include "bits/gthr.h"
63 #else
64 // GCC extension end
65 #if defined(__STL_SGI_THREADS)
66 #include <mutex.h>
67 #include <time.h>
68 #elif defined(__STL_PTHREADS)
69 #include <pthread.h>
70 #elif defined(__STL_UITHREADS)
71 #include <thread.h>
72 #include <synch.h>
73 #elif defined(__STL_WIN32THREADS)
74 #include <windows.h>
75 #endif
76 // GCC extension begin
77 #endif
78 // GCC extension end
79
80 namespace std
81 {
82
83 // Class _Refcount_Base provides a type, _RC_t, a data member,
84 // _M_ref_count, and member functions _M_incr and _M_decr, which perform
85 // atomic preincrement/predecrement.  The constructor initializes 
86 // _M_ref_count.
87
88 // Hack for SGI o32 compilers.
89 #if defined(__STL_SGI_THREADS) && !defined(__add_and_fetch) && \
90     (__mips < 3 || !(defined (_ABIN32) || defined(_ABI64)))
91 #  define __add_and_fetch(__l,__v) add_then_test((unsigned long*)__l,__v)  
92 #  define __test_and_set(__l,__v)  test_and_set(__l,__v)
93 #endif /* o32 */
94
95 struct _Refcount_Base
96 {
97   // The type _RC_t
98 # ifdef __STL_WIN32THREADS
99   typedef long _RC_t;
100 # else
101   typedef size_t _RC_t;
102 #endif
103   
104   // The data member _M_ref_count
105    volatile _RC_t _M_ref_count;
106
107   // Constructor
108 // GCC extension begin
109 #ifdef __STL_GTHREADS
110   __gthread_mutex_t _M_ref_count_lock;
111   _Refcount_Base(_RC_t __n) : _M_ref_count(__n)
112     {
113 #ifdef __GTHREAD_MUTEX_INIT
114       __gthread_mutex_t __tmp = __GTHREAD_MUTEX_INIT;
115       _M_ref_count_lock = __tmp;
116 #elif defined(__GTHREAD_MUTEX_INIT_FUNCTION)
117       __GTHREAD_MUTEX_INIT_FUNCTION (&_M_ref_count_lock);
118 #else
119 #error __GTHREAD_MUTEX_INIT or __GTHREAD_MUTEX_INIT_FUNCTION should be defined by gthr.h abstraction layer, report problem to libstdc++@gcc.gnu.org.
120 #endif
121     }
122 #else
123 // GCC extension end
124 # ifdef __STL_PTHREADS
125   pthread_mutex_t _M_ref_count_lock;
126   _Refcount_Base(_RC_t __n) : _M_ref_count(__n)
127     { pthread_mutex_init(&_M_ref_count_lock, 0); }
128 # elif defined(__STL_UITHREADS)
129   mutex_t         _M_ref_count_lock;
130   _Refcount_Base(_RC_t __n) : _M_ref_count(__n)
131     { mutex_init(&_M_ref_count_lock, USYNC_THREAD, 0); }
132 # else
133   _Refcount_Base(_RC_t __n) : _M_ref_count(__n) {}
134 # endif
135 // GCC extension begin
136 #endif
137 // GCC extension end
138
139 // GCC extension begin
140 #ifdef __STL_GTHREADS
141   void _M_incr() {
142     __gthread_mutex_lock(&_M_ref_count_lock);
143     ++_M_ref_count;
144     __gthread_mutex_unlock(&_M_ref_count_lock);
145   }
146   _RC_t _M_decr() {
147     __gthread_mutex_lock(&_M_ref_count_lock);
148     volatile _RC_t __tmp = --_M_ref_count;
149     __gthread_mutex_unlock(&_M_ref_count_lock);
150     return __tmp;
151   }
152 #else
153 // GCC extension end
154   // _M_incr and _M_decr
155 # ifdef __STL_SGI_THREADS
156   void _M_incr() {  __add_and_fetch(&_M_ref_count, 1); }
157   _RC_t _M_decr() { return __add_and_fetch(&_M_ref_count, (size_t) -1); }
158 # elif defined (__STL_WIN32THREADS)
159    void _M_incr() { InterlockedIncrement((_RC_t*)&_M_ref_count); }
160   _RC_t _M_decr() { return InterlockedDecrement((_RC_t*)&_M_ref_count); }
161 # elif defined(__STL_PTHREADS)
162   void _M_incr() {
163     pthread_mutex_lock(&_M_ref_count_lock);
164     ++_M_ref_count;
165     pthread_mutex_unlock(&_M_ref_count_lock);
166   }
167   _RC_t _M_decr() {
168     pthread_mutex_lock(&_M_ref_count_lock);
169     volatile _RC_t __tmp = --_M_ref_count;
170     pthread_mutex_unlock(&_M_ref_count_lock);
171     return __tmp;
172   }
173 # elif defined(__STL_UITHREADS)
174   void _M_incr() {
175     mutex_lock(&_M_ref_count_lock);
176     ++_M_ref_count;
177     mutex_unlock(&_M_ref_count_lock);
178   }
179   _RC_t _M_decr() {
180     mutex_lock(&_M_ref_count_lock);
181     /*volatile*/ _RC_t __tmp = --_M_ref_count;
182     mutex_unlock(&_M_ref_count_lock);
183     return __tmp;
184   }
185 # else  /* No threads */
186   void _M_incr() { ++_M_ref_count; }
187   _RC_t _M_decr() { return --_M_ref_count; }
188 # endif
189 // GCC extension begin
190 #endif
191 // GCC extension end
192 };
193
194 // Atomic swap on unsigned long
195 // This is guaranteed to behave as though it were atomic only if all
196 // possibly concurrent updates use _Atomic_swap.
197 // In some cases the operation is emulated with a lock.
198 // GCC extension begin
199 #ifdef __STL_GTHREADS
200 // We don't provide an _Atomic_swap in this configuration.  This only
201 // affects the use of ext/rope with threads.  Someone could add this
202 // later, if required.  You can start by cloning the __STL_PTHREADS
203 // path while making the obvious changes.  Later it could be optimized
204 // to use the atomicity.h abstraction layer from libstdc++-v3.
205 #else
206 // GCC extension end
207 # ifdef __STL_SGI_THREADS
208     inline unsigned long _Atomic_swap(unsigned long * __p, unsigned long __q) {
209 #       if __mips < 3 || !(defined (_ABIN32) || defined(_ABI64))
210             return test_and_set(__p, __q);
211 #       else
212             return __test_and_set(__p, (unsigned long)__q);
213 #       endif
214     }
215 # elif defined(__STL_WIN32THREADS)
216     inline unsigned long _Atomic_swap(unsigned long * __p, unsigned long __q) {
217         return (unsigned long) InterlockedExchange((LPLONG)__p, (LONG)__q);
218     }
219 # elif defined(__STL_PTHREADS)
220     // We use a template here only to get a unique initialized instance.
221     template<int __dummy>
222     struct _Swap_lock_struct {
223         static pthread_mutex_t _S_swap_lock;
224     };
225
226     template<int __dummy>
227     pthread_mutex_t
228     _Swap_lock_struct<__dummy>::_S_swap_lock = PTHREAD_MUTEX_INITIALIZER;
229
230     // This should be portable, but performance is expected
231     // to be quite awful.  This really needs platform specific
232     // code.
233     inline unsigned long _Atomic_swap(unsigned long * __p, unsigned long __q) {
234         pthread_mutex_lock(&_Swap_lock_struct<0>::_S_swap_lock);
235         unsigned long __result = *__p;
236         *__p = __q;
237         pthread_mutex_unlock(&_Swap_lock_struct<0>::_S_swap_lock);
238         return __result;
239     }
240 # elif defined(__STL_UITHREADS)
241     // We use a template here only to get a unique initialized instance.
242     template<int __dummy>
243     struct _Swap_lock_struct {
244         static mutex_t _S_swap_lock;
245     };
246
247     template<int __dummy>
248     mutex_t
249     _Swap_lock_struct<__dummy>::_S_swap_lock = DEFAULTMUTEX;
250
251     // This should be portable, but performance is expected
252     // to be quite awful.  This really needs platform specific
253     // code.
254     inline unsigned long _Atomic_swap(unsigned long * __p, unsigned long __q) {
255         mutex_lock(&_Swap_lock_struct<0>::_S_swap_lock);
256         unsigned long __result = *__p;
257         *__p = __q;
258         mutex_unlock(&_Swap_lock_struct<0>::_S_swap_lock);
259         return __result;
260     }
261 # elif defined (__STL_SOLARIS_THREADS)
262     // any better solutions ?
263     // We use a template here only to get a unique initialized instance.
264     template<int __dummy>
265     struct _Swap_lock_struct {
266         static mutex_t _S_swap_lock;
267     };
268
269 # if ( __STL_STATIC_TEMPLATE_DATA > 0 )
270     template<int __dummy>
271     mutex_t
272     _Swap_lock_struct<__dummy>::_S_swap_lock = DEFAULTMUTEX;
273 #  else
274     __DECLARE_INSTANCE(mutex_t, _Swap_lock_struct<__dummy>::_S_swap_lock, 
275                        =DEFAULTMUTEX);
276 # endif /* ( __STL_STATIC_TEMPLATE_DATA > 0 ) */
277
278     // This should be portable, but performance is expected
279     // to be quite awful.  This really needs platform specific
280     // code.
281     inline unsigned long _Atomic_swap(unsigned long * __p, unsigned long __q) {
282         mutex_lock(&_Swap_lock_struct<0>::_S_swap_lock);
283         unsigned long __result = *__p;
284         *__p = __q;
285         mutex_unlock(&_Swap_lock_struct<0>::_S_swap_lock);
286         return __result;
287     }
288 # else
289     static inline unsigned long _Atomic_swap(unsigned long * __p, unsigned long __q) {
290         unsigned long __result = *__p;
291         *__p = __q;
292         return __result;
293     }
294 # endif
295 // GCC extension begin
296 #endif
297 // GCC extension end
298
299 // Locking class.  Note that this class *does not have a constructor*.
300 // It must be initialized either statically, with __STL_MUTEX_INITIALIZER,
301 // or dynamically, by explicitly calling the _M_initialize member function.
302 // (This is similar to the ways that a pthreads mutex can be initialized.)
303 // There are explicit member functions for acquiring and releasing the lock.
304
305 // There is no constructor because static initialization is essential for
306 // some uses, and only a class aggregate (see section 8.5.1 of the C++
307 // standard) can be initialized that way.  That means we must have no
308 // constructors, no base classes, no virtual functions, and no private or
309 // protected members.
310
311 // Helper struct.  This is a workaround for various compilers that don't
312 // handle static variables in inline functions properly.
313 template <int __inst>
314 struct _STL_mutex_spin {
315   enum { __low_max = 30, __high_max = 1000 };
316   // Low if we suspect uniprocessor, high for multiprocessor.
317
318   static unsigned __max;
319   static unsigned __last;
320 };
321
322 template <int __inst>
323 unsigned _STL_mutex_spin<__inst>::__max = _STL_mutex_spin<__inst>::__low_max;
324
325 template <int __inst>
326 unsigned _STL_mutex_spin<__inst>::__last = 0;
327
328 // GCC extension begin
329 #if defined(__STL_GTHREADS)
330 #if !defined(__GTHREAD_MUTEX_INIT) && defined(__GTHREAD_MUTEX_INIT_FUNCTION)
331 extern __gthread_mutex_t _GLIBCPP_mutex;
332 extern __gthread_mutex_t *_GLIBCPP_mutex_address;
333 extern __gthread_once_t _GLIBCPP_once;
334 extern void _GLIBCPP_mutex_init (void);
335 extern void _GLIBCPP_mutex_address_init (void);
336 #endif
337 #endif
338 // GCC extension end
339
340 struct _STL_mutex_lock
341 {
342 // GCC extension begin
343 #if defined(__STL_GTHREADS)
344   // The class must be statically initialized with __STL_MUTEX_INITIALIZER.
345 #if !defined(__GTHREAD_MUTEX_INIT) && defined(__GTHREAD_MUTEX_INIT_FUNCTION)
346   volatile int _M_init_flag;
347   __gthread_once_t _M_once;
348 #endif
349   __gthread_mutex_t _M_lock;
350   void _M_initialize() {
351 #ifdef __GTHREAD_MUTEX_INIT
352     // There should be no code in this path given the usage rules above.
353 #elif defined(__GTHREAD_MUTEX_INIT_FUNCTION)
354     if (_M_init_flag) return;
355     if (__gthread_once (&_GLIBCPP_once, _GLIBCPP_mutex_init) != 0
356         && __gthread_active_p ())
357       abort ();
358     __gthread_mutex_lock (&_GLIBCPP_mutex);
359     if (!_M_init_flag) {
360         // Even though we have a global lock, we use __gthread_once to be
361         // absolutely certain the _M_lock mutex is only initialized once on
362         // multiprocessor systems.
363         _GLIBCPP_mutex_address = &_M_lock;
364         if (__gthread_once (&_M_once, _GLIBCPP_mutex_address_init) != 0
365             && __gthread_active_p ())
366           abort ();
367         _M_init_flag = 1;
368     }
369     __gthread_mutex_unlock (&_GLIBCPP_mutex);
370 #endif
371   }
372   void _M_acquire_lock() {
373 #if !defined(__GTHREAD_MUTEX_INIT) && defined(__GTHREAD_MUTEX_INIT_FUNCTION)
374     if (!_M_init_flag) _M_initialize();
375 #endif
376     __gthread_mutex_lock(&_M_lock);
377   }
378   void _M_release_lock() {
379 #if !defined(__GTHREAD_MUTEX_INIT) && defined(__GTHREAD_MUTEX_INIT_FUNCTION)
380     if (!_M_init_flag) _M_initialize();
381 #endif
382     __gthread_mutex_unlock(&_M_lock);
383   }
384 #else
385 // GCC extension end
386 #if defined(__STL_SGI_THREADS) || defined(__STL_WIN32THREADS)
387   // It should be relatively easy to get this to work on any modern Unix.
388   volatile unsigned long _M_lock;
389   void _M_initialize() { _M_lock = 0; }
390   static void _S_nsec_sleep(int __log_nsec) {
391 #     ifdef __STL_SGI_THREADS
392           struct timespec __ts;
393           /* Max sleep is 2**27nsec ~ 60msec      */
394           __ts.tv_sec = 0;
395           __ts.tv_nsec = 1L << __log_nsec;
396           nanosleep(&__ts, 0);
397 #     elif defined(__STL_WIN32THREADS)
398           if (__log_nsec <= 20) {
399               Sleep(0);
400           } else {
401               Sleep(1 << (__log_nsec - 20));
402           }
403 #     else
404 #       error unimplemented
405 #     endif
406   }
407   void _M_acquire_lock() {
408     volatile unsigned long* __lock = &this->_M_lock;
409
410     if (!_Atomic_swap((unsigned long*)__lock, 1)) {
411       return;
412     }
413     unsigned __my_spin_max = _STL_mutex_spin<0>::__max;
414     unsigned __my_last_spins = _STL_mutex_spin<0>::__last;
415     volatile unsigned __junk = 17;      // Value doesn't matter.
416     unsigned __i;
417     for (__i = 0; __i < __my_spin_max; __i++) {
418       if (__i < __my_last_spins/2 || *__lock) {
419         __junk *= __junk; __junk *= __junk;
420         __junk *= __junk; __junk *= __junk;
421         continue;
422       }
423       if (!_Atomic_swap((unsigned long*)__lock, 1)) {
424         // got it!
425         // Spinning worked.  Thus we're probably not being scheduled
426         // against the other process with which we were contending.
427         // Thus it makes sense to spin longer the next time.
428         _STL_mutex_spin<0>::__last = __i;
429         _STL_mutex_spin<0>::__max = _STL_mutex_spin<0>::__high_max;
430         return;
431       }
432     }
433     // We are probably being scheduled against the other process.  Sleep.
434     _STL_mutex_spin<0>::__max = _STL_mutex_spin<0>::__low_max;
435     for (__i = 0 ;; ++__i) {
436       int __log_nsec = __i + 6;
437
438       if (__log_nsec > 27) __log_nsec = 27;
439       if (!_Atomic_swap((unsigned long *)__lock, 1)) {
440         return;
441       }
442       _S_nsec_sleep(__log_nsec);
443     }
444   }
445   void _M_release_lock() {
446     volatile unsigned long* __lock = &_M_lock;
447 #   if defined(__STL_SGI_THREADS) && defined(__GNUC__) && __mips >= 3
448         asm("sync");
449         *__lock = 0;
450 #   elif defined(__STL_SGI_THREADS) && __mips >= 3 \
451          && (defined (_ABIN32) || defined(_ABI64))
452         __lock_release(__lock);
453 #   else 
454         *__lock = 0;
455         // This is not sufficient on many multiprocessors, since
456         // writes to protected variables and the lock may be reordered.
457 #   endif
458   }
459
460 // We no longer use win32 critical sections.
461 // They appear to be slower in the contention-free case,
462 // and they appear difficult to initialize without introducing a race.
463
464 #elif defined(__STL_PTHREADS)
465   pthread_mutex_t _M_lock;
466   void _M_initialize()   { pthread_mutex_init(&_M_lock, NULL); }
467   void _M_acquire_lock() { pthread_mutex_lock(&_M_lock); }
468   void _M_release_lock() { pthread_mutex_unlock(&_M_lock); }
469 #elif defined(__STL_UITHREADS)
470   mutex_t _M_lock;
471   void _M_initialize()   { mutex_init(&_M_lock, USYNC_THREAD, 0); }
472   void _M_acquire_lock() { mutex_lock(&_M_lock); }
473   void _M_release_lock() { mutex_unlock(&_M_lock); }
474 #else /* No threads */
475   void _M_initialize()   {}
476   void _M_acquire_lock() {}
477   void _M_release_lock() {}
478 #endif
479 // GCC extension begin
480 #endif
481 // GCC extension end
482 };
483
484 // GCC extension begin
485 #if defined(__STL_GTHREADS)
486 #ifdef __GTHREAD_MUTEX_INIT
487 #define __STL_MUTEX_INITIALIZER = { __GTHREAD_MUTEX_INIT }
488 #elif defined(__GTHREAD_MUTEX_INIT_FUNCTION)
489 #ifdef __GTHREAD_MUTEX_INIT_DEFAULT
490 #define __STL_MUTEX_INITIALIZER \
491   = { 0, __GTHREAD_ONCE_INIT, __GTHREAD_MUTEX_INIT_DEFAULT }
492 #else
493 #define __STL_MUTEX_INITIALIZER = { 0, __GTHREAD_ONCE_INIT }
494 #endif
495 #endif
496 #else
497 // GCC extension end
498 #ifdef __STL_PTHREADS
499 // Pthreads locks must be statically initialized to something other than
500 // the default value of zero.
501 #   define __STL_MUTEX_INITIALIZER = { PTHREAD_MUTEX_INITIALIZER }
502 #elif defined(__STL_UITHREADS)
503 // UIthreads locks must be statically initialized to something other than
504 // the default value of zero.
505 #   define __STL_MUTEX_INITIALIZER = { DEFAULTMUTEX }
506 #elif defined(__STL_SGI_THREADS) || defined(__STL_WIN32THREADS)
507 #   define __STL_MUTEX_INITIALIZER = { 0 }
508 #else
509 #   define __STL_MUTEX_INITIALIZER
510 #endif
511 // GCC extension begin
512 #endif
513 // GCC extension end
514
515
516 // A locking class that uses _STL_mutex_lock.  The constructor takes a
517 // reference to an _STL_mutex_lock, and acquires a lock.  The
518 // destructor releases the lock.  It's not clear that this is exactly
519 // the right functionality.  It will probably change in the future.
520
521 struct _STL_auto_lock
522 {
523   _STL_mutex_lock& _M_lock;
524   
525   _STL_auto_lock(_STL_mutex_lock& __lock) : _M_lock(__lock)
526     { _M_lock._M_acquire_lock(); }
527   ~_STL_auto_lock() { _M_lock._M_release_lock(); }
528
529 private:
530   void operator=(const _STL_auto_lock&);
531   _STL_auto_lock(const _STL_auto_lock&);
532 };
533
534 } // namespace std
535
536 #endif /* __SGI_STL_INTERNAL_THREADS_H */
537
538 // Local Variables:
539 // mode:C++
540 // End:
541