Thread.cpp 911 B

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