Add simple mutex

with this you can lock access to shared structures
This commit is contained in:
Moritz Bitsch 2020-10-16 16:23:09 +02:00
parent 31f2d9c602
commit 0f205ba2cc
2 changed files with 40 additions and 0 deletions

View file

@ -324,3 +324,28 @@ coio_active_throw()
throw std::logic_error("Not inside coroutine"); throw std::logic_error("Not inside coroutine");
} }
} }
CoioMutex::CoioMutex() {
owner = nullptr;
}
void
CoioMutex::lock() {
if (owner == nullptr) {
owner = coio_current;
} else {
waiting.push_back(coio_current);
coio_delay(-1);
}
}
void
CoioMutex::unlock() {
if (!waiting.empty()) {
owner = waiting.back();
waiting.pop_back();
coio_ready(owner);
} else {
owner = nullptr;
}
}

15
coio.h
View file

@ -17,6 +17,7 @@
#define COIO_H #define COIO_H
#include <functional> #include <functional>
#include <vector>
typedef struct CoioTask CoioTask; typedef struct CoioTask CoioTask;
typedef std::function<void()> coio_func; typedef std::function<void()> coio_func;
@ -44,4 +45,18 @@ coio_active();
void void
coio_active_throw(); coio_active_throw();
class CoioMutex {
CoioTask* owner;
std::vector<CoioTask*> waiting;
public:
CoioMutex();
~CoioMutex() = default;
CoioMutex(const CoioMutex&) = delete;
CoioMutex& operator=(const CoioMutex&) = delete;
void lock();
void unlock();
};
#endif #endif