summaryrefslogtreecommitdiff
path: root/shared/loki/Threads.h
blob: 8fb5d362aba47c53b982cd0a5f5b38c6d1233ae6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2001 by Andrei Alexandrescu
// This code accompanies the book:
// Alexandrescu, Andrei. "Modern C++ Design: Generic Programming and Design
//     Patterns Applied". Copyright (c) 2001. Addison-Wesley.
// Permission to use, copy, modify, distribute and sell this software for any
//     purpose is hereby granted without fee, provided that the above copyright
//     notice appear in all copies and that both that copyright notice and this
//     permission notice appear in supporting documentation.
// The author or Addison-Wesley Longman make no representations about the
//     suitability of this software for any purpose. It is provided "as is"
//     without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////
#ifndef LOKI_THREADS_INC_
#define LOKI_THREADS_INC_

// $Id: Threads.h 902 2008-11-10 05:47:06Z rich_sposato $


///  @defgroup  ThreadingGroup Threading
///  Policies to for the threading model:
///
///  - SingleThreaded
///  - ObjectLevelLockable
///  - ClassLevelLockable
///
///  All classes in Loki have configurable threading model.
///
///  The macro LOKI_DEFAULT_THREADING selects the default
///  threading model for certain components of Loki
///  (it affects only default template arguments)
///
///  \par Usage:
///
///  To use a specific threading model define
///
///  - nothing, single-theading is default
///  - LOKI_OBJECT_LEVEL_THREADING for object-level-threading
///  - LOKI_CLASS_LEVEL_THREADING for class-level-threading
///
///  \par Supported platfroms:
///
///  - Windows (windows.h)
///  - POSIX (pthread.h):
///    No recursive mutex support with pthread.
///    This means: calling Lock() on a Loki::Mutex twice from the
///    same thread before unlocking the mutex deadlocks the system.
///    To avoid this redesign your synchronization. See also:
///    http://sourceforge.net/tracker/index.php?func=detail&aid=1516182&group_id=29557&atid=396647


#include <cassert>

#if defined(LOKI_CLASS_LEVEL_THREADING) || defined(LOKI_OBJECT_LEVEL_THREADING)

#define LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL ::Loki::ClassLevelLockable

#if defined(LOKI_CLASS_LEVEL_THREADING) && !defined(LOKI_OBJECT_LEVEL_THREADING)
#define LOKI_DEFAULT_THREADING ::Loki::ClassLevelLockable
#else
#define LOKI_DEFAULT_THREADING ::Loki::ObjectLevelLockable
#endif

#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#define LOKI_WINDOWS_H
#else
#include <pthread.h>
#define LOKI_PTHREAD_H
#endif

#else

#define LOKI_DEFAULT_THREADING ::Loki::SingleThreaded
#define LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL ::Loki::SingleThreaded

#endif

#ifndef LOKI_DEFAULT_MUTEX
#define LOKI_DEFAULT_MUTEX ::Loki::Mutex
#endif

#ifdef LOKI_WINDOWS_H

#define LOKI_THREADS_MUTEX(x)           CRITICAL_SECTION (x);
#define LOKI_THREADS_MUTEX_INIT(x)      ::InitializeCriticalSection (x)
#define LOKI_THREADS_MUTEX_DELETE(x)    ::DeleteCriticalSection (x)
#define LOKI_THREADS_MUTEX_LOCK(x)      ::EnterCriticalSection (x)
#define LOKI_THREADS_MUTEX_UNLOCK(x)    ::LeaveCriticalSection (x)
#define LOKI_THREADS_LONG               LONG
#define LOKI_THREADS_MUTEX_CTOR(x)

#define LOKI_THREADS_ATOMIC_FUNCTIONS                                   \
        static IntType AtomicMultiply(volatile IntType& lval, const IntType val) \
        {                                                               \
            ::EnterCriticalSection( &atomic_mutex_ );                   \
            lval *= val;                                                \
            ::LeaveCriticalSection( &atomic_mutex_ );                   \
            return lval;                                                \
        }                                                               \
                                                                        \
        static IntType AtomicDivide(volatile IntType& lval, const IntType val)  \
        {                                                               \
            ::EnterCriticalSection( &atomic_mutex_ );                   \
            lval /= val;                                                \
            ::LeaveCriticalSection( &atomic_mutex_ );                   \
            return lval;                                                \
        }                                                               \
                                                                        \
        static IntType AtomicIncrement(volatile IntType& lval)          \
        {                                                               \
            ::EnterCriticalSection( &atomic_mutex_ );                   \
            ++lval;                                                     \
            ::LeaveCriticalSection( &atomic_mutex_ );                   \
            return lval;                                                \
        }                                                               \
                                                                        \
        static IntType AtomicDecrement(volatile IntType& lval)          \
        {                                                               \
            ::EnterCriticalSection( &atomic_mutex_ );                   \
            --lval;                                                     \
            ::LeaveCriticalSection( &atomic_mutex_ );                   \
            return lval;                                                \
        }                                                               \
                                                                        \
        static void AtomicAssign(volatile IntType& lval, const IntType val)   \
        { InterlockedExchange(&const_cast<IntType&>(lval), val); }      \
                                                                        \
        static void AtomicAssign(IntType& lval, volatile const IntType& val)  \
        { InterlockedExchange(&lval, val); }                            \
                                                                        \
        static IntType AtomicIncrement(volatile IntType& lval, const IntType compare, bool & matches )  \
        {                                                               \
            ::EnterCriticalSection( &atomic_mutex_ );                   \
            ++lval;                                                     \
            matches = ( lval == compare );                              \
            ::LeaveCriticalSection( &atomic_mutex_ );                   \
            return lval;                                                \
        }                                                               \
                                                                        \
        static IntType AtomicDecrement(volatile IntType& lval, const IntType compare, bool & matches )  \
        {                                                               \
            ::EnterCriticalSection( &atomic_mutex_ );                   \
            --lval;                                                     \
            matches = ( lval == compare );                              \
            ::LeaveCriticalSection( &atomic_mutex_ );                   \
            return lval;                                                \
        }                                                               \
                                                                        \
        static IntType AtomicAdd(volatile IntType& lval, const IntType val, const IntType compare, bool & matches )  \
        {                                                               \
            ::EnterCriticalSection( &atomic_mutex_ );                   \
            lval += val;                                                \
            matches = ( lval == compare );                              \
            ::LeaveCriticalSection( &atomic_mutex_ );                   \
            return lval;                                                \
        }                                                               \
                                                                        \
        static IntType AtomicSubtract(volatile IntType& lval, const IntType val, const IntType compare, bool & matches ) \
        {                                                               \
            ::EnterCriticalSection( &atomic_mutex_ );                   \
            lval -= val;                                                \
            matches = ( lval == compare );                              \
            ::LeaveCriticalSection( &atomic_mutex_ );                   \
            return lval;                                                \
        }                                                               \
                                                                        \
        static IntType AtomicMultiply(volatile IntType& lval, const IntType val, const IntType compare, bool & matches ) \
        {                                                               \
            ::EnterCriticalSection( &atomic_mutex_ );                   \
            lval *= val;                                                \
            matches = ( lval == compare );                              \
            ::LeaveCriticalSection( &atomic_mutex_ );                   \
            return lval;                                                \
        }                                                               \
                                                                        \
        static IntType AtomicDivide(volatile IntType& lval, const IntType val, const IntType compare, bool & matches )   \
        {                                                               \
            ::EnterCriticalSection( &atomic_mutex_ );                    \
            lval /= val;                                                \
            matches = ( lval == compare );                              \
            ::LeaveCriticalSection( &atomic_mutex_ );                    \
            return lval;                                                \
        }

#elif defined(LOKI_PTHREAD_H)


#define LOKI_THREADS_MUTEX(x)           pthread_mutex_t (x);

#define LOKI_THREADS_MUTEX_INIT(x)      ::pthread_mutex_init(x, 0)

// define to 1 to enable recursive mutex support
#if 0
// experimental recursive mutex support
#define LOKI_THREADS_MUTEX_CTOR(x)      : x(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
#else
// no recursive mutex support
#define LOKI_THREADS_MUTEX_CTOR(x)
#endif

#define LOKI_THREADS_MUTEX_DELETE(x)    ::pthread_mutex_destroy (x)
#define LOKI_THREADS_MUTEX_LOCK(x)      ::pthread_mutex_lock (x)
#define LOKI_THREADS_MUTEX_UNLOCK(x)    ::pthread_mutex_unlock (x)
#define LOKI_THREADS_LONG               long

#define LOKI_THREADS_ATOMIC(x)                                           \
                pthread_mutex_lock(&atomic_mutex_);                      \
                x;                                                       \
                pthread_mutex_unlock(&atomic_mutex_)

#define LOKI_THREADS_ATOMIC_FUNCTIONS                                \
    private:                                                         \
        static pthread_mutex_t atomic_mutex_;                        \
    public:                                                          \
        static IntType AtomicMultiply(volatile IntType& lval, const IntType val) \
        {                                                                \
            ::pthread_mutex_lock( &atomic_mutex_ );                      \
            lval *= val;                                                 \
            ::pthread_mutex_unlock( &atomic_mutex_ );                    \
            return lval;                                                 \
        }                                                                \
                                                                         \
        static IntType AtomicDivide(volatile IntType& lval, const IntType val) \
        {                                                                \
            ::pthread_mutex_lock( &atomic_mutex_ );                      \
            lval /= val;                                                 \
            ::pthread_mutex_unlock( &atomic_mutex_ );                    \
            return lval;                                                 \
        }                                                                \
                                                                         \
        static IntType AtomicIncrement(volatile IntType& lval)           \
        {                                                                \
            ::pthread_mutex_lock( &atomic_mutex_ );                      \
            ++lval;                                                      \
            ::pthread_mutex_unlock( &atomic_mutex_ );                    \
            return lval;                                                 \
        }                                                                \
                                                                         \
        static IntType AtomicDecrement(volatile IntType& lval)           \
        {                                                                \
            ::pthread_mutex_lock( &atomic_mutex_ );                      \
            --lval;                                                      \
            ::pthread_mutex_unlock( &atomic_mutex_ );                    \
            return lval;                                                 \
        }                                                                \
                                                                         \
        static void AtomicAssign(volatile IntType& lval, const IntType val) \
        {                                                                \
            ::pthread_mutex_lock( &atomic_mutex_ );                      \
            lval = val;                                                  \
            ::pthread_mutex_unlock( &atomic_mutex_ );                    \
            return lval;                                                 \
        }                                                                \
                                                                         \
        static void AtomicAssign(IntType& lval, volatile const IntType& val) \
        {                                                                \
            ::pthread_mutex_lock( &atomic_mutex_ );                      \
            lval = val;                                                  \
            ::pthread_mutex_unlock( &atomic_mutex_ );                    \
            return lval;                                                 \
        }                                                                \
                                                                         \
        static IntType AtomicIncrement(volatile IntType& lval, const IntType compare, bool & matches ) \
        {                                                                \
            ::pthread_mutex_lock( &atomic_mutex_ );                      \
            ++lval;                                                      \
            matches = ( compare == lval );                               \
            ::pthread_mutex_unlock( &atomic_mutex_ );                    \
            return lval;                                                 \
        }                                                                \
                                                                         \
        static IntType AtomicDecrement(volatile IntType& lval, const IntType compare, bool & matches ) \
        {                                                                \
            ::pthread_mutex_lock( &atomic_mutex_ );                      \
            --lval;                                                      \
            matches = ( compare == lval );                               \
            ::pthread_mutex_unlock( &atomic_mutex_ );                    \
            return lval;                                                 \
        }                                                                \
        static IntType AtomicMultiply(volatile IntType& lval, const IntType val, const IntType compare, bool & matches ) \
        {                                                               \
            ::pthread_mutex_lock( &atomic_mutex_ );                     \
            lval *= val;                                                \
            matches = ( lval == compare );                              \
            ::pthread_mutex_unlock( &atomic_mutex_ );                   \
            return lval;                                                \
        }                                                               \
                                                                        \
        static IntType AtomicDivide(volatile IntType& lval, const IntType val, const IntType compare, bool & matches ) \
        {                                                               \
            ::pthread_mutex_lock( &atomic_mutex_ );                     \
            lval /= val;                                                \
            matches = ( lval == compare );                              \
            ::pthread_mutex_unlock( &atomic_mutex_ );                   \
            return lval;                                                \
        }

#else // single threaded

#define LOKI_THREADS_MUTEX(x)
#define LOKI_THREADS_MUTEX_INIT(x)
#define LOKI_THREADS_MUTEX_DELETE(x)
#define LOKI_THREADS_MUTEX_LOCK(x)
#define LOKI_THREADS_MUTEX_UNLOCK(x)
#define LOKI_THREADS_LONG
#define LOKI_THREADS_MUTEX_CTOR(x)

#endif



namespace Loki
{

////////////////////////////////////////////////////////////////////////////////
///  \class Mutex
//
///  \ingroup ThreadingGroup
///  A simple and portable Mutex.  A default policy class for locking objects.
////////////////////////////////////////////////////////////////////////////////

class Mutex
{
public:
    Mutex() LOKI_THREADS_MUTEX_CTOR(mtx_)
    {
        LOKI_THREADS_MUTEX_INIT(&mtx_);
    }
    ~Mutex()
    {
        LOKI_THREADS_MUTEX_DELETE(&mtx_);
    }
    void Lock()
    {
        LOKI_THREADS_MUTEX_LOCK(&mtx_);
    }
    void Unlock()
    {
        LOKI_THREADS_MUTEX_UNLOCK(&mtx_);
    }
private:
    /// Copy-constructor not implemented.
    Mutex(const Mutex&);
    /// Copy-assignement operator not implemented.
    Mutex& operator = (const Mutex&);
    LOKI_THREADS_MUTEX(mtx_)
};


////////////////////////////////////////////////////////////////////////////////
///  \class SingleThreaded
///
///  \ingroup ThreadingGroup
///  Implementation of the ThreadingModel policy used by various classes
///  Implements a single-threaded model; no synchronization
////////////////////////////////////////////////////////////////////////////////
template <class Host, class MutexPolicy = LOKI_DEFAULT_MUTEX>
class SingleThreaded
{
public:
    /// \struct Lock
    /// Dummy Lock class
    struct Lock
    {
        Lock() {}
        explicit Lock(const SingleThreaded&) {}
        explicit Lock(const SingleThreaded*) {}
    };

    typedef Host VolatileType;

    typedef int IntType;

    static IntType AtomicAdd(volatile IntType& lval, const IntType val)
    { return lval += val; }

    static IntType AtomicSubtract(volatile IntType& lval, const IntType val)
    { return lval -= val; }

    static IntType AtomicMultiply(volatile IntType& lval, const IntType val)
    { return lval *= val; }

    static IntType AtomicDivide(volatile IntType& lval, const IntType val)
    { return lval /= val; }

    static IntType AtomicIncrement(volatile IntType& lval)
    { return ++lval; }

    static IntType AtomicDecrement(volatile IntType& lval)
    { return --lval; }

    static void AtomicAssign(volatile IntType& lval, const IntType val)
    { lval = val; }

    static void AtomicAssign(IntType& lval, volatile IntType& val)
    { lval = val; }

    static IntType AtomicAdd(volatile IntType& lval, const IntType val, const IntType compare, bool& matches )
    {
        lval += val;
        matches = ( lval == compare );
        return lval;
    }

    static IntType AtomicSubtract(volatile IntType& lval, const IntType val, const IntType compare, bool& matches )
    {
        lval -= val;
        matches = ( lval == compare );
        return lval;
    }

    static IntType AtomicMultiply(volatile IntType& lval, const IntType val, const IntType compare, bool& matches )
    {
        lval *= val;
        matches = ( lval == compare );
        return lval;
    }

    static IntType AtomicDivide(volatile IntType& lval, const IntType val, const IntType compare, bool& matches )
    {
        lval /= val;
        matches = ( lval == compare );
        return lval;
    }

    static IntType AtomicIncrement(volatile IntType& lval, const IntType compare, bool& matches )
    {
        ++lval;
        matches = ( lval == compare );
        return lval;
    }

    static IntType AtomicDecrement(volatile IntType& lval, const IntType compare, bool& matches )
    {
        --lval;
        matches = ( lval == compare );
        return lval;
    }

};


#if defined(LOKI_WINDOWS_H) || defined(LOKI_PTHREAD_H)

////////////////////////////////////////////////////////////////////////////////
///  \class ObjectLevelLockable
///
///  \ingroup ThreadingGroup
///  Implementation of the ThreadingModel policy used by various classes
///  Implements a object-level locking scheme
////////////////////////////////////////////////////////////////////////////////
template < class Host, class MutexPolicy = LOKI_DEFAULT_MUTEX >
class ObjectLevelLockable
{
    mutable MutexPolicy mtx_;

public:
    ObjectLevelLockable() : mtx_() {}

    ObjectLevelLockable(const ObjectLevelLockable&) : mtx_() {}

    ~ObjectLevelLockable() {}

    class Lock;
    friend class Lock;

    ///  \struct Lock
    ///  Lock class to lock on object level
    class Lock
    {
    public:

        /// Lock object
        explicit Lock(const ObjectLevelLockable& host) : host_(host)
        {
            host_.mtx_.Lock();
        }

        /// Lock object
        explicit Lock(const ObjectLevelLockable* host) : host_(*host)
        {
            host_.mtx_.Lock();
        }

        /// Unlock object
        ~Lock()
        {
            host_.mtx_.Unlock();
        }

    private:
        /// private by design of the object level threading
        Lock();
        Lock(const Lock&);
        Lock& operator=(const Lock&);
        const ObjectLevelLockable& host_;
    };

    typedef volatile Host VolatileType;

    typedef LOKI_THREADS_LONG IntType;

    LOKI_THREADS_ATOMIC_FUNCTIONS

};

#ifdef LOKI_PTHREAD_H
template <class Host, class MutexPolicy>
pthread_mutex_t ObjectLevelLockable<Host, MutexPolicy>::atomic_mutex_ = PTHREAD_MUTEX_INITIALIZER;
#endif

////////////////////////////////////////////////////////////////////////////////
///  \class ClassLevelLockable
///
///  \ingroup ThreadingGroup
///  Implementation of the ThreadingModel policy used by various classes
///  Implements a class-level locking scheme
////////////////////////////////////////////////////////////////////////////////
template <class Host, class MutexPolicy = LOKI_DEFAULT_MUTEX >
class ClassLevelLockable
{
    struct Initializer
    {
        bool init_;
        MutexPolicy mtx_;

        Initializer() : init_(false), mtx_()
        {
            init_ = true;
        }

        ~Initializer()
        {
            assert(init_);
        }
    };

    static Initializer initializer_;

public:

    class Lock;
    friend class Lock;

    ///  \struct Lock
    ///  Lock class to lock on class level
    class Lock
    {
    public:

        /// Lock class
        Lock()
        {
            assert(initializer_.init_);
            initializer_.mtx_.Lock();
        }

        /// Lock class
        explicit Lock(const ClassLevelLockable&)
        {
            assert(initializer_.init_);
            initializer_.mtx_.Lock();
        }

        /// Lock class
        explicit Lock(const ClassLevelLockable*)
        {
            assert(initializer_.init_);
            initializer_.mtx_.Lock();
        }

        /// Unlock class
        ~Lock()
        {
            assert(initializer_.init_);
            initializer_.mtx_.Unlock();
        }

    private:
        Lock(const Lock&);
        Lock& operator=(const Lock&);
    };

    typedef volatile Host VolatileType;

    typedef LOKI_THREADS_LONG IntType;

    LOKI_THREADS_ATOMIC_FUNCTIONS

};

#ifdef LOKI_PTHREAD_H
template <class Host, class MutexPolicy>
pthread_mutex_t ClassLevelLockable<Host, MutexPolicy>::atomic_mutex_ = PTHREAD_MUTEX_INITIALIZER;
#endif

template < class Host, class MutexPolicy >
typename ClassLevelLockable< Host, MutexPolicy >::Initializer
ClassLevelLockable< Host, MutexPolicy >::initializer_;

#endif // #if defined(LOKI_WINDOWS_H) || defined(LOKI_PTHREAD_H)

} // namespace Loki


#endif // end file guardian

bgstack15