Thread.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibThreading/Thread.h>
  7. #include <pthread.h>
  8. #include <string.h>
  9. #include <unistd.h>
  10. Threading::Thread::Thread(Function<intptr_t()> action, StringView thread_name)
  11. : Core::Object(nullptr)
  12. , m_action(move(action))
  13. , m_thread_name(thread_name.is_null() ? ""sv : thread_name)
  14. {
  15. register_property("thread_name", [&] { return JsonValue { m_thread_name }; });
  16. #if defined(AK_OS_SERENITY) || defined(AK_OS_LINUX)
  17. // FIXME: Print out a pretty TID for BSD and macOS platforms, too
  18. register_property("tid", [&] { return JsonValue { m_tid }; });
  19. #endif
  20. }
  21. Threading::Thread::~Thread()
  22. {
  23. if (m_tid && !m_detached) {
  24. dbgln("Destroying thread \"{}\"({}) while it is still running!", m_thread_name, m_tid);
  25. [[maybe_unused]] auto res = join();
  26. }
  27. }
  28. void Threading::Thread::start()
  29. {
  30. int rc = pthread_create(
  31. &m_tid,
  32. nullptr,
  33. [](void* arg) -> void* {
  34. Thread* self = static_cast<Thread*>(arg);
  35. auto exit_code = self->m_action();
  36. self->m_tid = 0;
  37. return reinterpret_cast<void*>(exit_code);
  38. },
  39. static_cast<void*>(this));
  40. VERIFY(rc == 0);
  41. #ifdef AK_OS_SERENITY
  42. if (!m_thread_name.is_empty()) {
  43. rc = pthread_setname_np(m_tid, m_thread_name.characters());
  44. VERIFY(rc == 0);
  45. }
  46. #endif
  47. dbgln("Started thread \"{}\", tid = {}", m_thread_name, m_tid);
  48. m_started = true;
  49. }
  50. void Threading::Thread::detach()
  51. {
  52. VERIFY(!m_detached);
  53. int rc = pthread_detach(m_tid);
  54. VERIFY(rc == 0);
  55. m_detached = true;
  56. }