summaryrefslogtreecommitdiff
path: root/Libraries/LibThread/Thread.cpp
blob: de5296f353be568326d060142157199344d46410 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <LibThread/Thread.h>
#include <unistd.h>

LibThread::Thread::Thread(Function<int()> action)
    : CObject(nullptr)
    , m_action(move(action))
{
}

LibThread::Thread::~Thread()
{
    if (m_tid != -1) {
        dbg() << "trying to destroy a running thread!";
        ASSERT_NOT_REACHED();
    }
}

void LibThread::Thread::start()
{
    int rc = create_thread([](void* arg) {
        Thread* self = static_cast<Thread*>(arg);
        int exit_code = self->m_action();
        self->m_tid = -1;
        exit_thread(exit_code);
        return exit_code;
    }, static_cast<void*>(this));

    ASSERT(rc > 0);
    dbg() << "Started a thread, tid = " << rc;
    m_tid = rc;
}

void LibThread::Thread::quit(int code)
{
    ASSERT(m_tid == gettid());

    m_tid = -1;
    exit_thread(code);
}