1
0
Fork 0
mirror of https://gitlab.com/niansa/commoncpp.git synced 2025-03-06 20:48:30 +01:00

Added more stuff

This commit is contained in:
niansa 2023-06-10 16:21:37 +02:00
parent 49cc9adb4a
commit dea0a97047
4 changed files with 125 additions and 2 deletions

View file

@ -4,8 +4,10 @@ set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_library(commoncpp STATIC
config.cpp include/commoncpp/config.hpp
utils.cpp include/commoncpp/utils.hpp)
config.cpp include/commoncpp/config.hpp
utils.cpp include/commoncpp/utils.hpp
pooled_thread.cpp include/commoncpp/pooled_thread.hpp
include/commoncpp/timer.hpp)
target_include_directories(commoncpp PUBLIC include/)
target_include_directories(commoncpp PRIVATE include/commoncpp/)

View file

@ -0,0 +1,62 @@
#ifndef SCHEDULED_THREAD_HPP
#define SCHEDULED_THREAD_HPP
#include <functional>
#include <future>
#include <mutex>
#include <queue>
#include <thread>
namespace commoncpp {
// This thread could be part of a thread pool
class PooledThread {
using QueueEntry = std::function<void ()>;
std::thread thread;
std::mutex queue_mutex;
std::queue<QueueEntry> queue;
std::mutex conditional_mutex;
std::condition_variable conditional_lock;
bool shutdown_requested = false;
bool joined = false;
void main_loop();
public:
PooledThread() {}
// MUST NOT already be running
void start() {
thread = std::thread([this] () {
main_loop();
});
}
// Can be called from anywhere
void enqueue(std::function<void ()>&& task_fcn) {
// Enqueue function
{
std::scoped_lock L(queue_mutex);
queue.emplace(QueueEntry{std::move(task_fcn)});
}
// Notify thread
conditional_lock.notify_one();
}
// MUST already be running
void wait() {
joined = true;
thread.join();
}
// MUST already be running
void shutdown() {
enqueue([this] () {
shutdown_requested = true;
});
}
};
}
#endif // SCHEDULED_THREAD_HPP

View file

@ -0,0 +1,26 @@
#ifndef TIMER_HPP
#define TIMER_HPP
#include <chrono>
namespace common {
class Timer {
std::chrono::time_point<std::chrono::high_resolution_clock> value;
public:
Timer() {
reset();
}
void reset() {
value = std::chrono::high_resolution_clock::now();
}
template<typename Unit = std::chrono::milliseconds>
auto get() {
auto duration = std::chrono::duration_cast<Unit>(std::chrono::high_resolution_clock::now() - value);
return duration.count();
}
};
}
#endif // TIMER_HPP

33
pooled_thread.cpp Normal file
View file

@ -0,0 +1,33 @@
#include "pooled_thread.hpp"
namespace commoncpp {
void PooledThread::main_loop() {
// Loop until shutdown is requested
while (!shutdown_requested) {
// Start all new tasks enqueued
{
std::unique_lock L(queue_mutex);
while (!queue.empty()) {
// Get queue entry
auto e = std::move(queue.front());
queue.pop();
// Unlock queue
L.unlock();
// Call start function
e();
// Lock queue
L.lock();
}
}
// Wait for work if there is none
if (queue.empty()) {
if (joined) break;
std::unique_lock<std::mutex> lock(conditional_mutex);
conditional_lock.wait(lock);
}
}
}
}