polybar/include/utils/concurrency.hpp

71 lines
1.2 KiB
C++
Raw Normal View History

2016-06-15 03:32:35 +00:00
#pragma once
2016-11-20 22:04:31 +00:00
#include <atomic>
2016-12-26 09:33:23 +00:00
#include <chrono>
2016-12-23 04:18:58 +00:00
#include <map>
2016-06-15 03:32:35 +00:00
#include <mutex>
2016-11-20 22:04:31 +00:00
#include <thread>
2016-06-15 03:32:35 +00:00
#include "common.hpp"
#include "utils/mixins.hpp"
2016-11-19 05:22:44 +00:00
POLYBAR_NS
2016-06-15 03:32:35 +00:00
2016-12-26 09:33:23 +00:00
namespace chrono =std::chrono;
using namespace std::chrono_literals;
2016-11-20 22:04:31 +00:00
namespace this_thread = std::this_thread;
2016-12-23 04:18:58 +00:00
using std::atomic;
using std::map;
using std::mutex;
2016-11-20 22:04:31 +00:00
using std::thread;
2016-12-26 09:33:23 +00:00
class spin_lock : public non_copyable_mixin<spin_lock> {
public:
struct no_backoff_strategy {
bool operator()();
};
struct yield_backoff_strategy {
bool operator()();
};
2016-06-15 03:32:35 +00:00
2016-12-26 09:33:23 +00:00
public:
explicit spin_lock() = default;
2016-06-15 03:32:35 +00:00
2016-12-26 09:33:23 +00:00
template <typename Backoff>
void lock(Backoff backoff) noexcept {
while (m_locked.test_and_set(std::memory_order_acquire)) {
backoff();
2016-06-15 03:32:35 +00:00
}
2016-12-26 09:33:23 +00:00
}
2016-06-15 03:32:35 +00:00
2016-12-26 09:33:23 +00:00
void lock() noexcept;
void unlock() noexcept;
2016-06-15 03:32:35 +00:00
2016-12-26 09:33:23 +00:00
protected:
std::atomic_flag m_locked{false};
};
template <typename T>
class mutex_wrapper : public T {
public:
template <typename... Args>
explicit mutex_wrapper(Args&&... args) : T(forward<Args>(args)...) {}
2016-06-15 03:32:35 +00:00
2016-12-26 09:33:23 +00:00
void lock() const noexcept {
m_mtx.lock();
}
void unlock() const noexcept {
m_mtx.unlock();
2016-06-15 03:32:35 +00:00
};
2016-12-23 04:18:58 +00:00
2016-12-26 09:33:23 +00:00
private:
mutable mutex m_mtx;
};
namespace concurrency_util {
2016-12-23 04:18:58 +00:00
size_t thread_id(const thread::id id);
2016-06-15 03:32:35 +00:00
}
2016-11-19 05:22:44 +00:00
POLYBAR_NS_END