Thread.cpp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include <LibThread/Thread.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. LibThread::Thread::Thread(Function<int()> action, StringView thread_name)
  5. : CObject(nullptr)
  6. , m_action(move(action))
  7. , m_thread_name(thread_name.is_null() ? "" : thread_name)
  8. {
  9. }
  10. LibThread::Thread::~Thread()
  11. {
  12. if (m_tid != -1) {
  13. dbg() << "trying to destroy a running thread!";
  14. ASSERT_NOT_REACHED();
  15. }
  16. }
  17. void LibThread::Thread::start()
  18. {
  19. int rc = pthread_create(
  20. &m_tid,
  21. nullptr,
  22. [](void* arg) -> void* {
  23. Thread* self = static_cast<Thread*>(arg);
  24. int exit_code = self->m_action();
  25. self->m_tid = -1;
  26. pthread_exit((void*)exit_code);
  27. return (void*)exit_code;
  28. },
  29. static_cast<void*>(this));
  30. ASSERT(rc == 0);
  31. if (!m_thread_name.is_empty()) {
  32. rc = pthread_setname_np(m_tid, m_thread_name.characters(), m_thread_name.length());
  33. ASSERT(rc == 0);
  34. }
  35. dbg() << "Started a thread, tid = " << m_tid;
  36. }
  37. void LibThread::Thread::quit(int code)
  38. {
  39. ASSERT(m_tid == gettid());
  40. m_tid = -1;
  41. pthread_exit((void*)code);
  42. }