thread.h (2465B)
1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors 2 // Licensed under the MIT License: 3 // 4 // Permission is hereby granted, free of charge, to any person obtaining a copy 5 // of this software and associated documentation files (the "Software"), to deal 6 // in the Software without restriction, including without limitation the rights 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 // copies of the Software, and to permit persons to whom the Software is 9 // furnished to do so, subject to the following conditions: 10 // 11 // The above copyright notice and this permission notice shall be included in 12 // all copies or substantial portions of the Software. 13 // 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 // THE SOFTWARE. 21 22 #pragma once 23 24 #include "common.h" 25 #include "function.h" 26 #include "exception.h" 27 28 KJ_BEGIN_HEADER 29 30 namespace kj { 31 32 class Thread { 33 // A thread! Pass a lambda to the constructor, and it runs in the thread. The destructor joins 34 // the thread. If the function throws an exception, it is rethrown from the thread's destructor 35 // (if not unwinding from another exception). 36 37 public: 38 explicit Thread(Function<void()> func); 39 KJ_DISALLOW_COPY(Thread); 40 41 ~Thread() noexcept(false); 42 43 #if !_WIN32 44 void sendSignal(int signo); 45 // Send a Unix signal to the given thread, using pthread_kill or an equivalent. 46 #endif 47 48 void detach(); 49 // Don't join the thread in ~Thread(). 50 51 private: 52 struct ThreadState { 53 ThreadState(Function<void()> func); 54 55 Function<void()> func; 56 Function<void(Function<void()>)> initializer; 57 kj::Maybe<kj::Exception> exception; 58 59 unsigned int refcount; 60 // Owned by the parent thread and the child thread. 61 62 void unref(); 63 }; 64 ThreadState* state; 65 66 #if _WIN32 67 void* threadHandle; 68 #else 69 unsigned long long threadId; // actually pthread_t 70 #endif 71 bool detached = false; 72 73 #if _WIN32 74 static unsigned long __stdcall runThread(void* ptr); 75 #else 76 static void* runThread(void* ptr); 77 #endif 78 }; 79 80 } // namespace kj 81 82 KJ_END_HEADER