Serenity Operating System
at hosted 74 lines 2.5 kB view raw
1/* 2 * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org> 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright notice, this 9 * list of conditions and the following disclaimer. 10 * 11 * 2. Redistributions in binary form must reproduce the above copyright notice, 12 * this list of conditions and the following disclaimer in the documentation 13 * and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 */ 26 27#include <LibThread/Thread.h> 28#include <pthread.h> 29#include <unistd.h> 30 31LibThread::Thread::Thread(Function<int()> action, StringView thread_name) 32 : Core::Object(nullptr) 33 , m_action(move(action)) 34 , m_thread_name(thread_name.is_null() ? "" : thread_name) 35{ 36} 37 38LibThread::Thread::~Thread() 39{ 40 if (m_tid) { 41 dbg() << "trying to destroy a running thread!"; 42 ASSERT_NOT_REACHED(); 43 } 44} 45 46void LibThread::Thread::start() 47{ 48 int rc = pthread_create( 49 &m_tid, 50 nullptr, 51 [](void* arg) -> void* { 52 Thread* self = static_cast<Thread*>(arg); 53 size_t exit_code = self->m_action(); 54 self->m_tid = 0; 55 pthread_exit((void*)exit_code); 56 return (void*)exit_code; 57 }, 58 static_cast<void*>(this)); 59 60 ASSERT(rc == 0); 61 if (!m_thread_name.is_empty()) { 62 rc = pthread_setname_np(m_tid, m_thread_name.characters()); 63 ASSERT(rc == 0); 64 } 65 dbg() << "Started a thread, tid = " << m_tid; 66} 67 68void LibThread::Thread::quit(void *code) 69{ 70 ASSERT(m_tid == pthread_self()); 71 72 m_tid = 0; 73 pthread_exit(code); 74}