Thread.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. * Copyright (c) 2021, Spencer Dixon <spencercdixon@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/DistinctNumeric.h>
  9. #include <AK/Function.h>
  10. #include <AK/Result.h>
  11. #include <AK/String.h>
  12. #include <LibCore/Object.h>
  13. #include <pthread.h>
  14. namespace Threading {
  15. TYPEDEF_DISTINCT_ORDERED_ID(intptr_t, ThreadError);
  16. class Thread final : public Core::Object {
  17. C_OBJECT(Thread);
  18. public:
  19. virtual ~Thread();
  20. void start();
  21. void detach();
  22. template<typename T = void>
  23. Result<T, ThreadError> join();
  24. String thread_name() const { return m_thread_name; }
  25. pthread_t tid() const { return m_tid; }
  26. private:
  27. explicit Thread(Function<intptr_t()> action, StringView thread_name = nullptr);
  28. Function<intptr_t()> m_action;
  29. pthread_t m_tid { 0 };
  30. String m_thread_name;
  31. bool m_detached { false };
  32. };
  33. template<typename T>
  34. Result<T, ThreadError> Thread::join()
  35. {
  36. void* thread_return = nullptr;
  37. int rc = pthread_join(m_tid, &thread_return);
  38. if (rc != 0) {
  39. return ThreadError { rc };
  40. }
  41. m_tid = 0;
  42. if constexpr (IsVoid<T>)
  43. return {};
  44. else
  45. return { static_cast<T>(thread_return) };
  46. }
  47. }