p26001-store-acs-soc-fw-app/util/Task.h
2026-09-28 21:33:04 +08:00

93 lines
2.5 KiB
C++

#ifndef EBDC071F_8F58_4C5D_ACB9_7C534616BEC5
#define EBDC071F_8F58_4C5D_ACB9_7C534616BEC5
/*
*******************************************************************************
* INCLUDE
*******************************************************************************
*/
#include <Poco/Thread.h>
#include <exception>
#include <functional>
#include <iostream>
#include <string>
#include <thread>
#include <tuple>
#include <utility>
namespace Util
{
/*
*******************************************************************************
* CLASS DECLARE
*******************************************************************************
*/
class Task
{
public:
Task(const std::string& name = "Anonymous");
public:
void run(std::function<void(std::atomic<bool>& isCancelled)> func);
template <typename Func, typename... Args> static void run2(Func&& func, Args&&... args)
{
run2WithError(std::forward<Func>(func), nullptr, std::forward<Args>(args)...);
}
template <typename Func, typename... Args>
static void run2WithError(Func&& func, std::function<void(std::exception_ptr)> onError, Args&&... args)
{
auto boundFunc = std::bind(std::forward<Func>(func), std::forward<Args>(args)...);
std::thread(
[boundFunc, onError]() mutable
{
try
{
boundFunc();
}
catch (const std::exception& e)
{
if (onError)
{
onError(std::current_exception());
}
else
{
std::cerr << "Util::Task::run2 exception: " << e.what() << std::endl;
}
}
catch (...)
{
if (onError)
{
onError(std::current_exception());
}
else
{
std::cerr << "Util::Task::run2 exception!" << std::endl;
}
}
})
.detach();
}
void cancel();
bool isRunning();
const std::string& name() const;
private:
const std::string _name;
std::atomic<bool> _isCancelled;
Poco::FastMutex _lock;
Poco::SharedPtr<Poco::Thread> _pThread;
};
inline const std::string& Task::name() const
{
return _name;
}
}
#endif