From b4eac549db531cfce63e70b4d3f962b6578e07d1 Mon Sep 17 00:00:00 2001 From: Michele Caini Date: Fri, 29 Jul 2016 17:39:44 +0200 Subject: [PATCH] WIP: thread.hpp -> added Thread --- src/uvw.hpp | 1 + src/uvw/thread.hpp | 85 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 src/uvw/thread.hpp diff --git a/src/uvw.hpp b/src/uvw.hpp index b8830a65..421e8b18 100644 --- a/src/uvw.hpp +++ b/src/uvw.hpp @@ -14,6 +14,7 @@ #include "uvw/process.hpp" #include "uvw/signal.hpp" #include "uvw/tcp.hpp" +#include "uvw/thread.hpp" #include "uvw/timer.hpp" #include "uvw/tty.hpp" #include "uvw/udp.hpp" diff --git a/src/uvw/thread.hpp b/src/uvw/thread.hpp new file mode 100644 index 00000000..c3b89bc7 --- /dev/null +++ b/src/uvw/thread.hpp @@ -0,0 +1,85 @@ +#pragma once + + +#include +#include +#include +#include +#include "loop.hpp" + + +namespace uvw { + + +class Thread final { + using InternalTask = std::function)>; + + static void createCallback(void *arg) { + Thread &thread = *(static_cast(arg)); + thread.task(thread.data); + } + + explicit Thread(std::shared_ptr ref, InternalTask t, std::shared_ptr d = nullptr) noexcept + : pLoop{std::move(ref)}, + data{std::move(d)}, + thread{}, + task{std::move(t)}, + err{0} + { } + +public: + using Task = InternalTask; + using Type = uv_thread_t; + + template + static std::shared_ptr create(Args&&... args) { + return std::shared_ptr{new Thread{std::forward(args)...}}; + } + + static Type self() noexcept { + return uv_thread_self(); + } + + static bool equal(const Thread &tl, const Thread &tr) noexcept { + return !(0 == uv_thread_equal(&tl.thread, &tr.thread)); + } + + ~Thread() { + uv_thread_join(&thread); + } + + bool run() noexcept { + err = uv_thread_create(&thread, &createCallback, this); + return static_cast(*this); + } + + bool join() noexcept { + err = uv_thread_join(&thread); + return static_cast(*this); + } + + explicit operator bool() const noexcept { return (0 == err); } + + int error() const noexcept { return err; } + + Loop& loop() const noexcept { return *pLoop; } + +private: + std::shared_ptr pLoop; + std::shared_ptr data; + uv_thread_t thread; + Task task; + int err; +}; + + +// TODO Thread-local storage +// TODO Once-only initialization +// TODO Mutex locks +// TODO Read-write locks +// TODO Semaphores +// TODO Conditions +// TODO Barriers + + +}