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

40 lines
1.1 KiB
C++

#include "pooled_thread.hpp"
#include <exception>
#include <iostream>
namespace common {
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
try {
e();
} catch (const std::exception& e) {
std::cerr << "Warning: Exception in pooled thread " << this << ": " << e.what() << std::endl;
}
// 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);
}
}
}
}