Statistics
| Branch: | Revision:

root / include / cttaslock.h @ ffa9279f

History | View | Annotate | Download (1.65 KB)

1 93d0d4d3 Simon Tenbusch
//==========================================================================
2
//  CTTASLOCK.H - part of
3
//
4
//                     Horizon/OMNeT++/OMNEST
5
//            Discrete System Simulation in C++
6
//
7
//
8
//  Declaration of the following classes:
9
//    cTTASLock: Encapsulating Test and Test and Set lock
10
//
11
//==========================================================================
12
13
/*--------------------------------------------------------------*
14 e118c57b Simon Tenbusch
 Copyright (C) 2011 Simon Tenbusch
15 93d0d4d3 Simon Tenbusch

16 e118c57b Simon Tenbusch
 This file is distributed WITHOUT ANY WARRANTY. See the file
17
 `license' for details on this and other legal matters.
18 93d0d4d3 Simon Tenbusch
 *--------------------------------------------------------------*/
19
20
#ifndef CTTASLOCK_H_
21
#define CTTASLOCK_H_
22
23
#ifdef ATOMIC_OPS_DEBUG
24 e118c57b Simon Tenbusch
#include "catomicopsdebug.h"
25 93d0d4d3 Simon Tenbusch
#else
26 e118c57b Simon Tenbusch
#include <atomic_ops.h>
27 93d0d4d3 Simon Tenbusch
#endif
28
29 b781545c Georg Kunz
class cTTASLock
30 e118c57b Simon Tenbusch
{
31 93d0d4d3 Simon Tenbusch
private:
32 e118c57b Simon Tenbusch
    AO_t lck;
33 93d0d4d3 Simon Tenbusch
34 b781545c Georg Kunz
    static const AO_t unlocked = 0;
35
    static const AO_t locked = 1;
36
37 93d0d4d3 Simon Tenbusch
public:
38 e118c57b Simon Tenbusch
    /**
39
     * Constructor.
40
     */
41 b781545c Georg Kunz
    cTTASLock()
42
    {
43
        AO_store_write(&lck, 0);
44
    }
45 e118c57b Simon Tenbusch
46
    /*
47
     * Locks the lock
48
     */
49 b781545c Georg Kunz
    inline void lock()
50
    {
51
        //
52
        // very simply TTAS based spinlock. Does not scale with the number of CPUs
53
        // and should thus be replaced by more complex locks.
54
        //
55
        while (true)
56
        {
57
            while (AO_load_full(&lck) == locked)
58
            {
59
                __asm__ ("pause");
60
            }
61
            if (AO_compare_and_swap_full(&lck, unlocked, locked) != 0)
62
            {
63
                return;
64
            }
65
        }
66
    }
67 e118c57b Simon Tenbusch
68
    /*
69
     * Unlocks the lock
70
     */
71 b781545c Georg Kunz
    inline void unlock()
72
    {
73
        AO_store_full(&lck, unlocked);
74
    }
75 93d0d4d3 Simon Tenbusch
76
};
77
78
#endif /* CTTASLOCK_H_ */