Thread.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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() ? "" : thread_name)
  14. {
  15. register_property("thread_name", [&] { return JsonValue { m_thread_name }; });
  16. register_property("tid", [&] { return JsonValue { m_tid }; });
  17. }
  18. Threading::Thread::~Thread()
  19. {
  20. if (m_tid && !m_detached) {
  21. dbgln("Destroying thread \"{}\"({}) while it is still running!", m_thread_name, m_tid);
  22. [[maybe_unused]] auto res = join();
  23. }
  24. }
  25. void Threading::Thread::start()
  26. {
  27. int rc = pthread_create(
  28. &m_tid,
  29. nullptr,
  30. [](void* arg) -> void* {
  31. Thread* self = static_cast<Thread*>(arg);
  32. auto exit_code = self->m_action();
  33. self->m_tid = 0;
  34. return reinterpret_cast<void*>(exit_code);
  35. },
  36. static_cast<void*>(this));
  37. VERIFY(rc == 0);
  38. if (!m_thread_name.is_empty()) {
  39. rc = pthread_setname_np(m_tid, m_thread_name.characters());
  40. VERIFY(rc == 0);
  41. }
  42. dbgln("Started thread \"{}\", tid = {}", m_thread_name, m_tid);
  43. }
  44. void Threading::Thread::detach()
  45. {
  46. VERIFY(!m_detached);
  47. int rc = pthread_detach(m_tid);
  48. VERIFY(rc == 0);
  49. m_detached = true;
  50. }