lokinet/llarp/threadpool.hpp

158 lines
2.8 KiB
C++
Raw Normal View History

2018-01-29 14:19:00 +00:00
#ifndef LLARP_THREADPOOL_HPP
#define LLARP_THREADPOOL_HPP
#include <llarp/threadpool.h>
#include <llarp/threading.hpp>
2018-01-29 14:19:00 +00:00
#include <functional>
#include <queue>
2018-01-29 14:27:24 +00:00
#include <thread>
2018-01-29 14:19:00 +00:00
#include <vector>
namespace llarp
{
namespace thread
{
2018-08-12 17:22:29 +00:00
typedef util::Mutex mtx_t;
typedef util::Lock lock_t;
struct Pool
{
virtual void
Spawn(size_t sz, const char* name);
void
QueueJob(const llarp_thread_job& job);
virtual void
Join();
void
Stop();
std::vector< std::thread > threads;
2018-01-29 14:27:24 +00:00
struct Job_t
{
uint32_t id;
2018-08-30 18:48:43 +00:00
void* user;
llarp_thread_work_func work;
Job_t() = default;
Job_t(uint32_t jobid, const llarp_thread_job& j)
: id(jobid), user(j.user), work(j.work)
{
}
bool
operator<(const Job_t& j) const
{
return id < j.id;
}
2018-08-30 18:48:43 +00:00
void
operator()() const
{
work(user);
}
};
std::priority_queue< Job_t > jobs;
uint32_t ids = 0;
mtx_t queue_mutex;
2018-08-12 17:22:29 +00:00
util::Condition condition;
util::Condition done;
bool stop;
};
2018-01-29 14:19:00 +00:00
struct IsolatedPool : public Pool
{
IsolatedPool(int flags) : Pool(), m_flags(flags)
{
}
virtual void
Spawn(size_t workers, const char* name);
2018-08-08 17:47:13 +00:00
void
Join();
2018-08-26 12:51:22 +00:00
/// isolate current thread
/// return true for success
/// return false for failure
/// set errno on fail
/// override me in subclass
virtual bool
IsolateCurrentProcess()
{
return true;
}
// override me to do specific setups after isolation
// return true for success
virtual bool
Isolated()
{
return true;
}
2018-08-18 14:01:21 +00:00
/// called when isolation failed
virtual void
Fail()
{
}
std::thread* m_isolated = nullptr;
int m_flags;
2018-08-26 12:51:22 +00:00
int m_IsolatedWorkers = 0;
const char* IsolatedName = nullptr;
virtual void
MainLoop()
{
}
};
2018-08-26 12:51:22 +00:00
struct _NetIsolatedPool : public IsolatedPool
{
2018-08-26 12:51:22 +00:00
_NetIsolatedPool(std::function< bool(void*, bool) > setupNet,
std::function< void(void*) > runMain, void* user);
/// implement me per platform
virtual bool
IsolateNetwork() = 0;
bool
IsolateCurrentProcess()
{
return IsolateNetwork();
}
bool
Isolated()
{
2018-08-18 14:01:21 +00:00
return m_NetSetup(m_user, true);
}
void
Fail()
{
m_NetSetup(m_user, false);
}
void
MainLoop()
{
m_RunMain(m_user);
}
2018-08-18 14:01:21 +00:00
std::function< bool(void*, bool) > m_NetSetup;
std::function< void(void*) > m_RunMain;
2018-08-09 19:02:17 +00:00
void* m_user;
};
} // namespace thread
2018-02-01 13:21:00 +00:00
} // namespace llarp
2018-01-29 14:19:00 +00:00
#endif