summaryrefslogtreecommitdiff
path: root/os/mutex.h
blob: d12331da2d9a445dd4f1304a3d073a4807e05dd2 (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
#ifndef MUTEX_H
#define MUTEX_H

class Mutex {
	private:
		uint8_t locked;
	public:
		Mutex() : locked(0) {}
		Mutex(uint8_t l) : locked(l) {}
		
		bool trylock() {
			uint8_t val;
			
			// Check if mutex is locked.
			asm volatile ("ldrexb %0, [%1]" : "=r" (val) : "r" (&locked));
			if(val) {
				return false;
			}
			
			// Try taking the lock.
			asm volatile ("strexb %0, %1, [%2]" : "=r" (val) : "r" (1), "r" (&locked));
			if(val) {
				return false;
			}
			
			asm volatile("dmb");
			return true;
		}
		
		void lock() {
			while(!trylock()) {
				Thread::yield();
			}
		}
		
		void unlock() {
			asm volatile("dmb");
			locked = 0;
		}
};

#endif