Update thread_pool and logger

This commit is contained in:
quqiOnfree 2025-02-23 09:58:07 +08:00
parent e3aedd510f
commit 27b560c67e
3 changed files with 29 additions and 19 deletions

View File

@ -17,8 +17,17 @@ class Logger
{
public:
Logger():
is_running_(true)
is_running_(false) {}
~Logger()
{
if (is_running_)
join();
}
void start()
{
is_running_ = true;
thread_ = std::thread([&]() {
while (true)
{
@ -36,34 +45,28 @@ public:
});
}
~Logger()
{
if (is_running_)
join();
}
template<typename... Args>
void cerr(Args... args)
void cerr(Args&&... args)
{
std::unique_lock<std::mutex> lock(mutex_);
msg_queue_.push(std::bind([](auto... args) {
std::cerr << generateTimeFormatString();
((std::cerr << args), ...);
std::cerr << std::endl;
}, std::move(args)...));
}, std::forward<Args>(args)...));
lock.unlock();
cv_.notify_all();
}
template<typename... Args>
void cout(Args... args)
void cout(Args&&... args)
{
std::unique_lock<std::mutex> lock(mutex_);
msg_queue_.push(std::bind([](auto... args) {
std::cout << generateTimeFormatString();
((std::cout << args), ...);
std::cout << std::endl;
}, std::move(args)...));
}, std::forward<Args>(args)...));
lock.unlock();
cv_.notify_all();
}

View File

@ -16,8 +16,17 @@ class ThreadPool
public:
ThreadPool():
thread_num_(std::thread::hardware_concurrency() * 2),
is_running_(true)
is_running_(false) {}
~ThreadPool() noexcept
{
if (is_running_)
join();
}
void start()
{
is_running_ = true;
work_threads_ = std::make_unique<std::thread[]>(thread_num_);
for (unsigned int i = 0; i < thread_num_; ++i)
{
@ -40,12 +49,6 @@ public:
}
}
~ThreadPool() noexcept
{
if (is_running_)
join();
}
template<class Func, class... Args>
void submit(Func&& func, Args&&... args)
{

View File

@ -45,7 +45,7 @@ void processFileTask(fs::path filePath, fs::path outputFolder)
}
catch (const std::invalid_argument &e)
{
logger.cerr(BOLDRED, "[Exception] ", RESET, RED, e.what(), RESET, " '", filePath.u8string(), "'");
logger.cerr(BOLDRED, "[Exception] ", RESET, RED, std::string(e.what()), RESET, " '", filePath.u8string(), "'");
}
catch (...)
{
@ -198,6 +198,8 @@ int main(int argc, char **argv)
}
}
}
logger.start();
thread_pool.start();
if (thread_pool.joinable())
thread_pool.join();
if (logger.joinable())
@ -226,6 +228,8 @@ int main(int argc, char **argv)
processFile(filePathU8, "");
}
}
logger.start();
thread_pool.start();
if (thread_pool.joinable())
thread_pool.join();
if (logger.joinable())