YAHAL
Yet Another Hardware Abstraction Library
Loading...
Searching...
No Matches
mutex.h
1// ---------------------------------------------
2// This file is part of
3// _ _ __ _ _ __ __
4// ( \/ ) /__\ ( )_( ) /__\ ( )
5// \ / /(__)\ ) _ ( /(__)\ )(__
6// (__)(__)(__)(_) (_)(__)(__)(____)
7//
8// Yet Another HW Abstraction Library
9// Copyright (C) Andreas Terstegge
10// BSD Licensed (see file LICENSE)
11//
12// ---------------------------------------------
13//
14// A simple mutex implementation with the typical
15// lock() / unlock() / try_lock() methods.
16// See mutex_interface.h for more information.
17
18#ifndef _MUTEX_H_
19#define _MUTEX_H_
20
21#include <cassert>
22#include "mutex_interface.h"
23#include "lock_base_interface.h"
24#include "task.h"
25
26template<typename T>
27class mutex : public mutex_interface {
28public:
29 explicit mutex(MUTEX::mutex_type type = MUTEX::BLOCK) : _type(type), _task(nullptr) { }
30
31 inline void lock() override {
32 while (!try_lock())
33 {
34 switch(_type) {
35 case MUTEX::ACTIVE_WAIT: {
36 continue;
37 }
38 case MUTEX::YIELD: {
39 task::yield();
40 break;
41 }
42 case MUTEX::BLOCK: {
43 // Make sure there is no context switch
44 // during the block operation
45 task::enterCritical();
46 task::currentTask()->block(&_lock);
47 task::leaveCritical();
48 task::yield();
49 }
50 }
51 }
52 // Store which task did get the lock...
53 _task = task::currentTask();
54 }
55
56 inline void unlock() override {
57 if (_task){
58 assert(task::currentTask() == _task);
59 }
60 _task = nullptr;
61 _lock.unlock();
62 }
63
64 inline bool try_lock() override {
65 bool res = _lock.try_lock();
66 if (res) {
67 _task = task::currentTask();
68 }
69 return res;
70 }
71
72 // No copy, no assignment
73 mutex (const mutex &) = delete;
74 mutex & operator= (const mutex &) = delete;
75
76private:
77 T _lock;
78 MUTEX::mutex_type _type;
79 task * _task;
80};
81
82#endif // _MUTEX_H_
Definition mutex.h:27
Definition task.h:39