namespace ucl {
- class Thread : public NonCopyable {
+ class Thread final : public NonCopyable {
public:
- explicit Thread(bool createSuspended = false);
- virtual ~Thread();
+ Thread();
+ template <class FUNC>
+ explicit Thread(FUNC &&func);
+ ~Thread();
+
bool wasStarted() const;
bool wasJoinded() const;
- bool start();
+
+ template <class FUNC>
+ bool start(FUNC &&func);
void join();
+
pthread_t *getHandle();
- protected:
- virtual void execute() = 0;
+
private:
+ std::function<void()> m_func;
pthread_t m_thread;
bool m_wasStarted;
bool m_wasJoined;
namespace ucl {
- inline Thread::Thread(bool createSuspended) :
+ inline Thread::Thread() :
m_thread(),
m_wasStarted(false),
m_wasJoined(false)
{
- if (!createSuspended) {
- start();
- }
+ }
+
+ template <class FUNC>
+ inline Thread::Thread(FUNC &&func) :
+ Thread()
+ {
+ start(func);
}
inline Thread::~Thread()
return m_wasJoined;
}
- inline bool Thread::start()
+ template <class FUNC>
+ inline bool Thread::start(FUNC &&func)
{
if (m_wasStarted) {
UCL_WLOG("Already started!");
return false;
}
+ m_func = std::forward<FUNC>(func);
const int res = pthread_create(&m_thread, NULL,
[](void *data) -> void *
{
- static_cast<Thread *>(data)->execute();
+ static_cast<Thread *>(data)->m_func();
return nullptr;
},
this);
if (res != 0) {
UCL_ELOG("pthread_create() failed: %d", res);
+ m_func = {};
return false;
}
m_wasStarted = true;
}
m_wasJoined = true;
pthread_join(m_thread, NULL);
+ m_func = {};
}
inline pthread_t *Thread::getHandle()