File: mutex.5c

package info (click to toggle)
nickle 2.91
  • links: PTS
  • area: main
  • in suites: bookworm
  • size: 3,660 kB
  • sloc: ansic: 27,438; yacc: 1,873; lex: 915; makefile: 230; sh: 41; lisp: 1
file content (98 lines) | stat: -rw-r--r-- 2,110 bytes parent folder | download | duplicates (9)
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
/*
 * Mutexes
 *
 * Mutexes can be held by only one thread
 * at a time, the following exceptions may
 * be raised:
 *
 *  exception deadlock (mutex m, thread self)
 *
 *	Raised when a thread attempts to reacquire the mutex
 *
 *  exception notowned (mutex m, thread self, mutex_owner owner)
 *
 *	Raised when a thread attempts to release a mutex not owned by it.
 */

/* A mutex is either owned by a thread or nobody */
typedef union { 
    thread  owner; 
    void    nobody; 
} mutex_owner;

public typedef struct { 
    semaphore	sem; 
    mutex_owner owner; 
} mutex_struct;

public typedef *mutex_struct mutex;

namespace Mutex {

    public typedef *mutex_struct mutex;

    public exception deadlock (mutex m, thread self)
	/*
	 * raised when attempting to lock a mutex locked by self
	 */;
    public exception notowned (mutex m, thread self, mutex_owner owner)
	/*
	 * raised when attempting to release a mutex which is not locked
	 */;

    public bool acquire (mutex m)
	/*
	 * Lock 'm'
	 */
    {
	if (m->owner == (mutex_owner.owner) Thread::current())
	    raise deadlock (m, Thread::current ());
	Semaphore::wait(m->sem);
	m->owner = (mutex_owner.owner) Thread::current ();
	return true;
    }

    public bool try_acquire (mutex m)
	/*
	 * If 'm' is unlocked, acquire (m) and return true
	 * else return false
	 */
    {
	if (m->owner == (mutex_owner.owner) Thread::current())
	    raise deadlock (m, Thread::current());
        bool ret = Semaphore::test (m->sem);
        if (ret)
	    m->owner = (mutex_owner.owner) Thread::current();
	return ret;
    }

    public void release (mutex m)
	/*
	 * Unlock 'm'
	 */
    {
	if (m->owner != (mutex_owner.owner) Thread::current())
	    raise notowned (m, Thread::current (), m->owner);
	m->owner = mutex_owner.nobody;
	Semaphore::signal (m->sem);
    }

    public mutex_owner owner (mutex m)
	/*
	 * Return owner of 'm'
	 */
    {
	return m->owner;
    }
    
    public mutex new ()
	/*
	 * Create new (unlocked) mutex
	 */
    {
	return reference ((mutex_struct) { 
	    .sem = Semaphore::new (1),
	    .owner = mutex_owner.nobody
	});
    }
}