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#if defined(__GNUC__) && !KJ_HEADER_WARNINGS
25#pragma GCC system_header
26#endif
27
28#include "common.h"
29#include "function.h"
30#include "exception.h"
31
32namespace kj {
33
34class Thread {
35 // A thread! Pass a lambda to the constructor, and it runs in the thread. The destructor joins
36 // the thread. If the function throws an exception, it is rethrown from the thread's destructor
37 // (if not unwinding from another exception).
38
39public:
40 explicit Thread(Function<void()> func);
41 KJ_DISALLOW_COPY(Thread);
42
43 ~Thread() noexcept(false);
44
45#if !_WIN32
46 void sendSignal(int signo);
47 // Send a Unix signal to the given thread, using pthread_kill or an equivalent.
48#endif
49
50 void detach();
51 // Don't join the thread in ~Thread().
52
53private:
54 struct ThreadState {
55 ThreadState(Function<void()> func);
56
57 Function<void()> func;
58 Function<void(Function<void()>)> initializer;
59 kj::Maybe<kj::Exception> exception;
60
61 unsigned int refcount;
62 // Owned by the parent thread and the child thread.
63
64 void unref();
65 };
66 ThreadState* state;
67
68#if _WIN32
69 void* threadHandle;
70#else
71 unsigned long long threadId; // actually pthread_t
72#endif
73 bool detached = false;
74
75#if _WIN32
76 static unsigned long __stdcall runThread(void* ptr);
77#else
78 static void* runThread(void* ptr);
79#endif
80};
81
82} // namespace kj
83