Thread.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. AK_TYPEDEF_DISTINCT_ORDERED_ID(intptr_t, ThreadError);
  16. class Thread final : public Core::Object {
  17. C_OBJECT(Thread);
  18. public:
  19. virtual ~Thread();
  20. ErrorOr<void> set_priority(int priority);
  21. ErrorOr<int> get_priority() const;
  22. void start();
  23. void detach();
  24. template<typename T = void>
  25. Result<T, ThreadError> join();
  26. String thread_name() const { return m_thread_name; }
  27. pthread_t tid() const { return m_tid; }
  28. bool is_started() const { return m_started; }
  29. private:
  30. explicit Thread(Function<intptr_t()> action, StringView thread_name = {});
  31. Function<intptr_t()> m_action;
  32. pthread_t m_tid { 0 };
  33. String m_thread_name;
  34. bool m_detached { false };
  35. bool m_started { false };
  36. };
  37. template<typename T>
  38. Result<T, ThreadError> Thread::join()
  39. {
  40. void* thread_return = nullptr;
  41. int rc = pthread_join(m_tid, &thread_return);
  42. if (rc != 0) {
  43. return ThreadError { rc };
  44. }
  45. m_tid = 0;
  46. if constexpr (IsVoid<T>)
  47. return {};
  48. else
  49. return { static_cast<T>(thread_return) };
  50. }
  51. }