1
0
Fork 0
mirror of https://github.com/polybar/polybar.git synced 2024-11-11 13:50:56 -05:00
polybar/include/utils/concurrency.hpp

71 lines
1.2 KiB
C++
Raw Normal View History

2016-06-14 23:32:35 -04:00
#pragma once
2016-11-20 17:04:31 -05:00
#include <atomic>
2016-12-26 04:33:23 -05:00
#include <chrono>
2016-12-22 23:18:58 -05:00
#include <map>
2016-06-14 23:32:35 -04:00
#include <mutex>
2016-11-20 17:04:31 -05:00
#include <thread>
2016-06-14 23:32:35 -04:00
#include "common.hpp"
#include "utils/mixins.hpp"
2016-11-19 00:22:44 -05:00
POLYBAR_NS
2016-06-14 23:32:35 -04:00
2016-12-26 04:33:23 -05:00
namespace chrono =std::chrono;
using namespace std::chrono_literals;
2016-11-20 17:04:31 -05:00
namespace this_thread = std::this_thread;
2016-12-22 23:18:58 -05:00
using std::atomic;
using std::map;
using std::mutex;
2016-11-20 17:04:31 -05:00
using std::thread;
2016-12-26 04:33:23 -05: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-14 23:32:35 -04:00
2016-12-26 04:33:23 -05:00
public:
explicit spin_lock() = default;
2016-06-14 23:32:35 -04:00
2016-12-26 04:33:23 -05:00
template <typename Backoff>
void lock(Backoff backoff) noexcept {
while (m_locked.test_and_set(std::memory_order_acquire)) {
backoff();
2016-06-14 23:32:35 -04:00
}
2016-12-26 04:33:23 -05:00
}
2016-06-14 23:32:35 -04:00
2016-12-26 04:33:23 -05:00
void lock() noexcept;
void unlock() noexcept;
2016-06-14 23:32:35 -04:00
2016-12-26 04:33:23 -05: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-14 23:32:35 -04:00
2016-12-26 04:33:23 -05:00
void lock() const noexcept {
m_mtx.lock();
}
void unlock() const noexcept {
m_mtx.unlock();
2016-06-14 23:32:35 -04:00
};
2016-12-22 23:18:58 -05:00
2016-12-26 04:33:23 -05:00
private:
mutable mutex m_mtx;
};
namespace concurrency_util {
2016-12-22 23:18:58 -05:00
size_t thread_id(const thread::id id);
2016-06-14 23:32:35 -04:00
}
2016-11-19 00:22:44 -05:00
POLYBAR_NS_END