Thread.cpp 795 B

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