1// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2// for details. All rights reserved. Use of this source code is governed by a
3// BSD-style license that can be found in the LICENSE file.
4
5#ifndef RUNTIME_BIN_THREAD_H_
6#define RUNTIME_BIN_THREAD_H_
7
8#include "platform/globals.h"
9
10namespace dart {
11namespace bin {
12class Thread;
13class Mutex;
14class Monitor;
15} // namespace bin
16} // namespace dart
17
18// Declare the OS-specific types ahead of defining the generic classes.
19#if defined(HOST_OS_ANDROID)
20#include "bin/thread_android.h"
21#elif defined(HOST_OS_FUCHSIA)
22#include "bin/thread_fuchsia.h"
23#elif defined(HOST_OS_LINUX)
24#include "bin/thread_linux.h"
25#elif defined(HOST_OS_MACOS)
26#include "bin/thread_macos.h"
27#elif defined(HOST_OS_WINDOWS)
28#include "bin/thread_win.h"
29#else
30#error Unknown target os.
31#endif
32
33namespace dart {
34namespace bin {
35
36class Thread {
37 public:
38 static const ThreadLocalKey kUnsetThreadLocalKey;
39 static const ThreadId kInvalidThreadId;
40
41 typedef void (*ThreadStartFunction)(uword parameter);
42
43 // Start a thread running the specified function. Returns 0 if the
44 // thread started successfuly and a system specific error code if
45 // the thread failed to start.
46 static int Start(const char* name,
47 ThreadStartFunction function,
48 uword parameters);
49
50 static ThreadLocalKey CreateThreadLocal();
51 static void DeleteThreadLocal(ThreadLocalKey key);
52 static uword GetThreadLocal(ThreadLocalKey key) {
53 return ThreadInlineImpl::GetThreadLocal(key);
54 }
55 static void SetThreadLocal(ThreadLocalKey key, uword value);
56 static intptr_t GetMaxStackSize();
57 static ThreadId GetCurrentThreadId();
58 static intptr_t ThreadIdToIntPtr(ThreadId id);
59 static bool Compare(ThreadId a, ThreadId b);
60
61 static void InitOnce();
62
63 private:
64 DISALLOW_ALLOCATION();
65 DISALLOW_IMPLICIT_CONSTRUCTORS(Thread);
66};
67
68class Mutex {
69 public:
70 Mutex();
71 ~Mutex();
72
73 void Lock();
74 bool TryLock();
75 void Unlock();
76
77 private:
78 MutexData data_;
79
80 DISALLOW_COPY_AND_ASSIGN(Mutex);
81};
82
83class Monitor {
84 public:
85 enum WaitResult { kNotified, kTimedOut };
86
87 static const int64_t kNoTimeout = 0;
88
89 Monitor();
90 ~Monitor();
91
92 void Enter();
93 void Exit();
94
95 // Wait for notification or timeout.
96 WaitResult Wait(int64_t millis);
97 WaitResult WaitMicros(int64_t micros);
98
99 // Notify waiting threads.
100 void Notify();
101 void NotifyAll();
102
103 private:
104 MonitorData data_; // OS-specific data.
105
106 DISALLOW_COPY_AND_ASSIGN(Monitor);
107};
108
109} // namespace bin
110} // namespace dart
111
112#endif // RUNTIME_BIN_THREAD_H_
113