henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2004 The WebRTC Project Authors. All rights reserved. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license |
| 5 | * that can be found in the LICENSE file in the root of the source |
| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 | |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 11 | #ifndef RTC_BASE_THREAD_H_ |
| 12 | #define RTC_BASE_THREAD_H_ |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 13 | |
Yves Gerey | 988cc08 | 2018-10-23 12:03:01 +0200 | [diff] [blame] | 14 | #include <stdint.h> |
Jonas Olsson | a4d8737 | 2019-07-05 19:08:33 +0200 | [diff] [blame] | 15 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 16 | #include <list> |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 17 | #include <map> |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 18 | #include <memory> |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 19 | #include <queue> |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 20 | #include <set> |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 21 | #include <string> |
Yves Gerey | 988cc08 | 2018-10-23 12:03:01 +0200 | [diff] [blame] | 22 | #include <type_traits> |
Danil Chapovalov | 7c323ad | 2022-09-08 13:13:53 +0200 | [diff] [blame] | 23 | #include <utility> |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 24 | #include <vector> |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 25 | |
Ali Tofigh | 7fa9057 | 2022-03-17 15:47:49 +0100 | [diff] [blame] | 26 | #include "absl/strings/string_view.h" |
| 27 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 28 | #if defined(WEBRTC_POSIX) |
| 29 | #include <pthread.h> |
| 30 | #endif |
Henrik Boström | 2deee4b | 2022-01-20 11:58:05 +0100 | [diff] [blame] | 31 | #include "absl/base/attributes.h" |
Danil Chapovalov | 4bcf809 | 2022-07-06 19:42:34 +0200 | [diff] [blame] | 32 | #include "absl/functional/any_invocable.h" |
Danil Chapovalov | 8931345 | 2019-11-29 12:56:43 +0100 | [diff] [blame] | 33 | #include "api/function_view.h" |
Danil Chapovalov | 912b3b8 | 2019-11-22 15:52:40 +0100 | [diff] [blame] | 34 | #include "api/task_queue/task_queue_base.h" |
Danil Chapovalov | 4bcf809 | 2022-07-06 19:42:34 +0200 | [diff] [blame] | 35 | #include "api/units/time_delta.h" |
Mirko Bonadei | 481e345 | 2021-07-30 13:57:25 +0200 | [diff] [blame] | 36 | #include "rtc_base/checks.h" |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 37 | #include "rtc_base/platform_thread_types.h" |
Steve Anton | 10542f2 | 2019-01-11 09:11:00 -0800 | [diff] [blame] | 38 | #include "rtc_base/socket_server.h" |
Danil Chapovalov | 3ab76d9 | 2022-09-23 12:39:21 +0200 | [diff] [blame] | 39 | #include "rtc_base/synchronization/mutex.h" |
Mirko Bonadei | 35214fc | 2019-09-23 14:54:28 +0200 | [diff] [blame] | 40 | #include "rtc_base/system/rtc_export.h" |
Yves Gerey | 988cc08 | 2018-10-23 12:03:01 +0200 | [diff] [blame] | 41 | #include "rtc_base/thread_annotations.h" |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 42 | |
| 43 | #if defined(WEBRTC_WIN) |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 44 | #include "rtc_base/win32.h" |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 45 | #endif |
| 46 | |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 47 | #if RTC_DCHECK_IS_ON |
Danil Chapovalov | 7c323ad | 2022-09-08 13:13:53 +0200 | [diff] [blame] | 48 | // Counts how many `Thread::BlockingCall` are made from within a scope and logs |
| 49 | // the number of blocking calls at the end of the scope. |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 50 | #define RTC_LOG_THREAD_BLOCK_COUNT() \ |
| 51 | rtc::Thread::ScopedCountBlockingCalls blocked_call_count_printer( \ |
| 52 | [func = __func__](uint32_t actual_block, uint32_t could_block) { \ |
| 53 | auto total = actual_block + could_block; \ |
| 54 | if (total) { \ |
| 55 | RTC_LOG(LS_WARNING) << "Blocking " << func << ": total=" << total \ |
| 56 | << " (actual=" << actual_block \ |
| 57 | << ", could=" << could_block << ")"; \ |
| 58 | } \ |
| 59 | }) |
| 60 | |
| 61 | // Adds an RTC_DCHECK_LE that checks that the number of blocking calls are |
| 62 | // less than or equal to a specific value. Use to avoid regressing in the |
| 63 | // number of blocking thread calls. |
| 64 | // Note: Use of this macro, requires RTC_LOG_THREAD_BLOCK_COUNT() to be called |
| 65 | // first. |
Tomas Gunnarsson | 89f3dd5 | 2021-04-14 12:54:10 +0200 | [diff] [blame] | 66 | #define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x) \ |
| 67 | do { \ |
| 68 | blocked_call_count_printer.set_minimum_call_count_for_callback(x + 1); \ |
| 69 | RTC_DCHECK_LE(blocked_call_count_printer.GetTotalBlockedCallCount(), x); \ |
| 70 | } while (0) |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 71 | #else |
| 72 | #define RTC_LOG_THREAD_BLOCK_COUNT() |
| 73 | #define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x) |
| 74 | #endif |
| 75 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 76 | namespace rtc { |
| 77 | |
| 78 | class Thread; |
| 79 | |
Mirko Bonadei | 35214fc | 2019-09-23 14:54:28 +0200 | [diff] [blame] | 80 | class RTC_EXPORT ThreadManager { |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 81 | public: |
| 82 | static const int kForever = -1; |
| 83 | |
| 84 | // Singleton, constructor and destructor are private. |
| 85 | static ThreadManager* Instance(); |
| 86 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 87 | static void Add(Thread* message_queue); |
| 88 | static void Remove(Thread* message_queue); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 89 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 90 | // For testing purposes, for use with a simulated clock. |
| 91 | // Ensures that all message queues have processed delayed messages |
| 92 | // up until the current point in time. |
| 93 | static void ProcessAllMessageQueuesForTesting(); |
| 94 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 95 | Thread* CurrentThread(); |
| 96 | void SetCurrentThread(Thread* thread); |
Sebastian Jansson | 178a685 | 2020-01-14 11:12:26 +0100 | [diff] [blame] | 97 | // Allows changing the current thread, this is intended for tests where we |
| 98 | // want to simulate multiple threads running on a single physical thread. |
| 99 | void ChangeCurrentThreadForTest(Thread* thread); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 100 | |
| 101 | // Returns a thread object with its thread_ ivar set |
| 102 | // to whatever the OS uses to represent the thread. |
| 103 | // If there already *is* a Thread object corresponding to this thread, |
| 104 | // this method will return that. Otherwise it creates a new Thread |
| 105 | // object whose wrapped() method will return true, and whose |
| 106 | // handle will, on Win32, be opened with only synchronization privileges - |
| 107 | // if you need more privilegs, rather than changing this method, please |
| 108 | // write additional code to adjust the privileges, or call a different |
| 109 | // factory method of your own devising, because this one gets used in |
| 110 | // unexpected contexts (like inside browser plugins) and it would be a |
| 111 | // shame to break it. It is also conceivable on Win32 that we won't even |
| 112 | // be able to get synchronization privileges, in which case the result |
| 113 | // will have a null handle. |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 114 | Thread* WrapCurrentThread(); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 115 | void UnwrapCurrentThread(); |
| 116 | |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 117 | #if RTC_DCHECK_IS_ON |
Artem Titov | 96e3b99 | 2021-07-26 16:03:14 +0200 | [diff] [blame] | 118 | // Registers that a Send operation is to be performed between `source` and |
| 119 | // `target`, while checking that this does not cause a send cycle that could |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 120 | // potentially cause a deadlock. |
| 121 | void RegisterSendAndCheckForCycles(Thread* source, Thread* target); |
| 122 | #endif |
| 123 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 124 | private: |
| 125 | ThreadManager(); |
| 126 | ~ThreadManager(); |
| 127 | |
Byoungchan Lee | 14af762 | 2022-01-12 05:24:58 +0900 | [diff] [blame] | 128 | ThreadManager(const ThreadManager&) = delete; |
| 129 | ThreadManager& operator=(const ThreadManager&) = delete; |
| 130 | |
Sebastian Jansson | 178a685 | 2020-01-14 11:12:26 +0100 | [diff] [blame] | 131 | void SetCurrentThreadInternal(Thread* thread); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 132 | void AddInternal(Thread* message_queue); |
| 133 | void RemoveInternal(Thread* message_queue); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 134 | void ProcessAllMessageQueuesInternal(); |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 135 | #if RTC_DCHECK_IS_ON |
| 136 | void RemoveFromSendGraph(Thread* thread) RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_); |
| 137 | #endif |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 138 | |
| 139 | // This list contains all live Threads. |
| 140 | std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_); |
| 141 | |
Danil Chapovalov | c3c8934 | 2023-01-02 09:21:29 +0000 | [diff] [blame] | 142 | webrtc::Mutex crit_; |
| 143 | |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 144 | #if RTC_DCHECK_IS_ON |
| 145 | // Represents all thread seand actions by storing all send targets per thread. |
| 146 | // This is used by RegisterSendAndCheckForCycles. This graph has no cycles |
| 147 | // since we will trigger a CHECK failure if a cycle is introduced. |
| 148 | std::map<Thread*, std::set<Thread*>> send_graph_ RTC_GUARDED_BY(crit_); |
| 149 | #endif |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 150 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 151 | #if defined(WEBRTC_POSIX) |
| 152 | pthread_key_t key_; |
| 153 | #endif |
| 154 | |
| 155 | #if defined(WEBRTC_WIN) |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 156 | const DWORD key_; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 157 | #endif |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 158 | }; |
| 159 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 160 | // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread(). |
| 161 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 162 | class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase { |
tommi | a8a3515 | 2017-07-13 05:47:25 -0700 | [diff] [blame] | 163 | public: |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 164 | static const int kForever = -1; |
| 165 | |
| 166 | // Create a new Thread and optionally assign it to the passed |
| 167 | // SocketServer. Subclasses that override Clear should pass false for |
| 168 | // init_queue and call DoInit() from their constructor to prevent races |
| 169 | // with the ThreadManager using the object while the vtable is still |
| 170 | // being created. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 171 | explicit Thread(SocketServer* ss); |
| 172 | explicit Thread(std::unique_ptr<SocketServer> ss); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 173 | |
Taylor Brandstetter | 0867260 | 2018-03-02 15:20:33 -0800 | [diff] [blame] | 174 | // Constructors meant for subclasses; they should call DoInit themselves and |
Artem Titov | 96e3b99 | 2021-07-26 16:03:14 +0200 | [diff] [blame] | 175 | // pass false for `do_init`, so that DoInit is called only on the fully |
Taylor Brandstetter | 0867260 | 2018-03-02 15:20:33 -0800 | [diff] [blame] | 176 | // instantiated class, which avoids a vptr data race. |
| 177 | Thread(SocketServer* ss, bool do_init); |
| 178 | Thread(std::unique_ptr<SocketServer> ss, bool do_init); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 179 | |
| 180 | // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or |
| 181 | // guarantee Stop() is explicitly called before the subclass is destroyed). |
| 182 | // This is required to avoid a data race between the destructor modifying the |
| 183 | // vtable, and the Thread::PreRun calling the virtual method Run(). |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 184 | |
| 185 | // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL |
| 186 | // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race |
| 187 | // between the destructor modifying the vtable, and the ThreadManager |
| 188 | // calling Clear on the object from a different thread. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 189 | ~Thread() override; |
| 190 | |
Byoungchan Lee | 14af762 | 2022-01-12 05:24:58 +0900 | [diff] [blame] | 191 | Thread(const Thread&) = delete; |
| 192 | Thread& operator=(const Thread&) = delete; |
| 193 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 194 | static std::unique_ptr<Thread> CreateWithSocketServer(); |
| 195 | static std::unique_ptr<Thread> Create(); |
| 196 | static Thread* Current(); |
| 197 | |
Danil Chapovalov | 7c323ad | 2022-09-08 13:13:53 +0200 | [diff] [blame] | 198 | // Used to catch performance regressions. Use this to disallow BlockingCall |
| 199 | // for a given scope. If a synchronous call is made while this is in |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 200 | // effect, an assert will be triggered. |
| 201 | // Note that this is a single threaded class. |
| 202 | class ScopedDisallowBlockingCalls { |
| 203 | public: |
| 204 | ScopedDisallowBlockingCalls(); |
Sebastian Jansson | 9debe5a | 2019-03-22 15:42:38 +0100 | [diff] [blame] | 205 | ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete; |
| 206 | ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) = |
| 207 | delete; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 208 | ~ScopedDisallowBlockingCalls(); |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 209 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 210 | private: |
| 211 | Thread* const thread_; |
| 212 | const bool previous_state_; |
| 213 | }; |
| 214 | |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 215 | #if RTC_DCHECK_IS_ON |
| 216 | class ScopedCountBlockingCalls { |
| 217 | public: |
| 218 | ScopedCountBlockingCalls(std::function<void(uint32_t, uint32_t)> callback); |
| 219 | ScopedCountBlockingCalls(const ScopedDisallowBlockingCalls&) = delete; |
| 220 | ScopedCountBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) = |
| 221 | delete; |
| 222 | ~ScopedCountBlockingCalls(); |
| 223 | |
| 224 | uint32_t GetBlockingCallCount() const; |
| 225 | uint32_t GetCouldBeBlockingCallCount() const; |
| 226 | uint32_t GetTotalBlockedCallCount() const; |
| 227 | |
Tomas Gunnarsson | 89f3dd5 | 2021-04-14 12:54:10 +0200 | [diff] [blame] | 228 | void set_minimum_call_count_for_callback(uint32_t minimum) { |
| 229 | min_blocking_calls_for_callback_ = minimum; |
| 230 | } |
| 231 | |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 232 | private: |
| 233 | Thread* const thread_; |
| 234 | const uint32_t base_blocking_call_count_; |
| 235 | const uint32_t base_could_be_blocking_call_count_; |
Tomas Gunnarsson | 89f3dd5 | 2021-04-14 12:54:10 +0200 | [diff] [blame] | 236 | // The minimum number of blocking calls required in order to issue the |
| 237 | // result_callback_. This is used by RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN to |
| 238 | // tame log spam. |
| 239 | // By default we always issue the callback, regardless of callback count. |
| 240 | uint32_t min_blocking_calls_for_callback_ = 0; |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 241 | std::function<void(uint32_t, uint32_t)> result_callback_; |
| 242 | }; |
| 243 | |
| 244 | uint32_t GetBlockingCallCount() const; |
| 245 | uint32_t GetCouldBeBlockingCallCount() const; |
| 246 | #endif |
| 247 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 248 | SocketServer* socketserver(); |
| 249 | |
| 250 | // Note: The behavior of Thread has changed. When a thread is stopped, |
| 251 | // futher Posts and Sends will fail. However, any pending Sends and *ready* |
| 252 | // Posts (as opposed to unexpired delayed Posts) will be delivered before |
| 253 | // Get (or Peek) returns false. By guaranteeing delivery of those messages, |
| 254 | // we eliminate the race condition when an MessageHandler and Thread |
| 255 | // may be destroyed independently of each other. |
| 256 | virtual void Quit(); |
| 257 | virtual bool IsQuitting(); |
| 258 | virtual void Restart(); |
| 259 | // Not all message queues actually process messages (such as SignalThread). |
| 260 | // In those cases, it's important to know, before posting, that it won't be |
| 261 | // Processed. Normally, this would be true until IsQuitting() is true. |
| 262 | virtual bool IsProcessingMessagesForTesting(); |
| 263 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 264 | // Amount of time until the next message can be retrieved |
| 265 | virtual int GetDelay(); |
| 266 | |
| 267 | bool empty() const { return size() == 0u; } |
| 268 | size_t size() const { |
Danil Chapovalov | 3ab76d9 | 2022-09-23 12:39:21 +0200 | [diff] [blame] | 269 | webrtc::MutexLock lock(&mutex_); |
Danil Chapovalov | 207f853 | 2022-08-24 12:19:46 +0200 | [diff] [blame] | 270 | return messages_.size() + delayed_messages_.size(); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 271 | } |
| 272 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 273 | bool IsCurrent() const; |
| 274 | |
| 275 | // Sleeps the calling thread for the specified number of milliseconds, during |
| 276 | // which time no processing is performed. Returns false if sleeping was |
| 277 | // interrupted by a signal (POSIX only). |
| 278 | static bool SleepMs(int millis); |
| 279 | |
| 280 | // Sets the thread's name, for debugging. Must be called before Start(). |
Artem Titov | 96e3b99 | 2021-07-26 16:03:14 +0200 | [diff] [blame] | 281 | // If `obj` is non-null, its value is appended to `name`. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 282 | const std::string& name() const { return name_; } |
Ali Tofigh | 7fa9057 | 2022-03-17 15:47:49 +0100 | [diff] [blame] | 283 | bool SetName(absl::string_view name, const void* obj); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 284 | |
Harald Alvestrand | ba69442 | 2021-01-27 21:52:14 +0000 | [diff] [blame] | 285 | // Sets the expected processing time in ms. The thread will write |
Danil Chapovalov | 7c323ad | 2022-09-08 13:13:53 +0200 | [diff] [blame] | 286 | // log messages when Dispatch() takes more time than this. |
Harald Alvestrand | ba69442 | 2021-01-27 21:52:14 +0000 | [diff] [blame] | 287 | // Default is 50 ms. |
| 288 | void SetDispatchWarningMs(int deadline); |
| 289 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 290 | // Starts the execution of the thread. |
Niels Möller | d2e5013 | 2019-06-11 09:24:14 +0200 | [diff] [blame] | 291 | bool Start(); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 292 | |
| 293 | // Tells the thread to stop and waits until it is joined. |
| 294 | // Never call Stop on the current thread. Instead use the inherited Quit |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 295 | // function which will exit the base Thread without terminating the |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 296 | // underlying OS thread. |
| 297 | virtual void Stop(); |
| 298 | |
| 299 | // By default, Thread::Run() calls ProcessMessages(kForever). To do other |
| 300 | // work, override Run(). To receive and dispatch messages, call |
| 301 | // ProcessMessages occasionally. |
| 302 | virtual void Run(); |
| 303 | |
Danil Chapovalov | 7c323ad | 2022-09-08 13:13:53 +0200 | [diff] [blame] | 304 | // Convenience method to invoke a functor on another thread. |
| 305 | // Blocks the current thread until execution is complete. |
| 306 | // Ex: thread.BlockingCall([&] { result = MyFunctionReturningBool(); }); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 307 | // NOTE: This function can only be called when synchronous calls are allowed. |
| 308 | // See ScopedDisallowBlockingCalls for details. |
Danil Chapovalov | 7c323ad | 2022-09-08 13:13:53 +0200 | [diff] [blame] | 309 | // NOTE: Blocking calls are DISCOURAGED, consider if what you're doing can |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 310 | // be achieved with PostTask() and callbacks instead. |
Danil Chapovalov | 7c323ad | 2022-09-08 13:13:53 +0200 | [diff] [blame] | 311 | virtual void BlockingCall(FunctionView<void()> functor); |
| 312 | |
| 313 | template <typename Functor, |
| 314 | typename ReturnT = std::invoke_result_t<Functor>, |
| 315 | typename = typename std::enable_if_t<!std::is_void_v<ReturnT>>> |
| 316 | ReturnT BlockingCall(Functor&& functor) { |
Danil Chapovalov | 8931345 | 2019-11-29 12:56:43 +0100 | [diff] [blame] | 317 | ReturnT result; |
Danil Chapovalov | 7c323ad | 2022-09-08 13:13:53 +0200 | [diff] [blame] | 318 | BlockingCall([&] { result = std::forward<Functor>(functor)(); }); |
Danil Chapovalov | 8931345 | 2019-11-29 12:56:43 +0100 | [diff] [blame] | 319 | return result; |
| 320 | } |
| 321 | |
Danil Chapovalov | 7c323ad | 2022-09-08 13:13:53 +0200 | [diff] [blame] | 322 | // Allows BlockingCall to specified `thread`. Thread never will be |
| 323 | // dereferenced and will be used only for reference-based comparison, so |
| 324 | // instance can be safely deleted. If NDEBUG is defined and RTC_DCHECK_IS_ON |
| 325 | // is undefined do nothing. |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 326 | void AllowInvokesToThread(Thread* thread); |
Tomas Gunnarsson | abdb470 | 2020-09-05 18:43:36 +0200 | [diff] [blame] | 327 | |
Mirko Bonadei | 481e345 | 2021-07-30 13:57:25 +0200 | [diff] [blame] | 328 | // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined do nothing. |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 329 | void DisallowAllInvokes(); |
Artem Titov | 96e3b99 | 2021-07-26 16:03:14 +0200 | [diff] [blame] | 330 | // Returns true if `target` was allowed by AllowInvokesToThread() or if no |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 331 | // calls were made to AllowInvokesToThread and DisallowAllInvokes. Otherwise |
| 332 | // returns false. |
Mirko Bonadei | 481e345 | 2021-07-30 13:57:25 +0200 | [diff] [blame] | 333 | // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined always returns |
Mirko Bonadei | 8c185fc | 2021-07-21 13:12:38 +0200 | [diff] [blame] | 334 | // true. |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 335 | bool IsInvokeToThreadAllowed(rtc::Thread* target); |
| 336 | |
Danil Chapovalov | 912b3b8 | 2019-11-22 15:52:40 +0100 | [diff] [blame] | 337 | // From TaskQueueBase |
Danil Chapovalov | 4bcf809 | 2022-07-06 19:42:34 +0200 | [diff] [blame] | 338 | void Delete() override; |
| 339 | void PostTask(absl::AnyInvocable<void() &&> task) override; |
| 340 | void PostDelayedTask(absl::AnyInvocable<void() &&> task, |
| 341 | webrtc::TimeDelta delay) override; |
| 342 | void PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task, |
| 343 | webrtc::TimeDelta delay) override; |
| 344 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 345 | // ProcessMessages will process I/O and dispatch messages until: |
| 346 | // 1) cms milliseconds have elapsed (returns true) |
| 347 | // 2) Stop() is called (returns false) |
| 348 | bool ProcessMessages(int cms); |
| 349 | |
| 350 | // Returns true if this is a thread that we created using the standard |
| 351 | // constructor, false if it was created by a call to |
| 352 | // ThreadManager::WrapCurrentThread(). The main thread of an application |
| 353 | // is generally not owned, since the OS representation of the thread |
| 354 | // obviously exists before we can get to it. |
| 355 | // You cannot call Start on non-owned threads. |
| 356 | bool IsOwned(); |
| 357 | |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 358 | // Expose private method IsRunning() for tests. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 359 | // |
| 360 | // DANGER: this is a terrible public API. Most callers that might want to |
| 361 | // call this likely do not have enough control/knowledge of the Thread in |
| 362 | // question to guarantee that the returned value remains true for the duration |
| 363 | // of whatever code is conditionally executing because of the return value! |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 364 | bool RunningForTest() { return IsRunning(); } |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 365 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 366 | // These functions are public to avoid injecting test hooks. Don't call them |
| 367 | // outside of tests. |
| 368 | // This method should be called when thread is created using non standard |
| 369 | // method, like derived implementation of rtc::Thread and it can not be |
| 370 | // started by calling Start(). This will set started flag to true and |
| 371 | // owned to false. This must be called from the current thread. |
| 372 | bool WrapCurrent(); |
| 373 | void UnwrapCurrent(); |
| 374 | |
Karl Wiberg | 3256225 | 2019-02-21 13:38:30 +0100 | [diff] [blame] | 375 | // Sets the per-thread allow-blocking-calls flag to false; this is |
| 376 | // irrevocable. Must be called on this thread. |
| 377 | void DisallowBlockingCalls() { SetAllowBlockingCalls(false); } |
| 378 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 379 | protected: |
Sebastian Jansson | 6ce033a | 2020-01-22 10:12:56 +0100 | [diff] [blame] | 380 | class CurrentThreadSetter : CurrentTaskQueueSetter { |
| 381 | public: |
| 382 | explicit CurrentThreadSetter(Thread* thread) |
| 383 | : CurrentTaskQueueSetter(thread), |
| 384 | manager_(rtc::ThreadManager::Instance()), |
| 385 | previous_(manager_->CurrentThread()) { |
| 386 | manager_->ChangeCurrentThreadForTest(thread); |
| 387 | } |
| 388 | ~CurrentThreadSetter() { manager_->ChangeCurrentThreadForTest(previous_); } |
| 389 | |
| 390 | private: |
| 391 | rtc::ThreadManager* const manager_; |
| 392 | rtc::Thread* const previous_; |
| 393 | }; |
| 394 | |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 395 | // DelayedMessage goes into a priority queue, sorted by trigger time. Messages |
| 396 | // with the same trigger time are processed in num_ (FIFO) order. |
Danil Chapovalov | d44e341 | 2022-09-16 17:26:10 +0200 | [diff] [blame] | 397 | struct DelayedMessage { |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 398 | bool operator<(const DelayedMessage& dmsg) const { |
Danil Chapovalov | d44e341 | 2022-09-16 17:26:10 +0200 | [diff] [blame] | 399 | return (dmsg.run_time_ms < run_time_ms) || |
| 400 | ((dmsg.run_time_ms == run_time_ms) && |
| 401 | (dmsg.message_number < message_number)); |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 402 | } |
| 403 | |
Danil Chapovalov | d44e341 | 2022-09-16 17:26:10 +0200 | [diff] [blame] | 404 | int64_t delay_ms; // for debugging |
| 405 | int64_t run_time_ms; |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 406 | // Monotonicaly incrementing number used for ordering of messages |
| 407 | // targeted to execute at the same time. |
Danil Chapovalov | d44e341 | 2022-09-16 17:26:10 +0200 | [diff] [blame] | 408 | uint32_t message_number; |
| 409 | // std::priority_queue doesn't allow to extract elements, but functor |
| 410 | // is move-only and thus need to be changed when pulled out of the |
| 411 | // priority queue. That is ok because `functor` doesn't affect operator< |
| 412 | mutable absl::AnyInvocable<void() &&> functor; |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 413 | }; |
| 414 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 415 | // Perform initialization, subclasses must call this from their constructor |
| 416 | // if false was passed as init_queue to the Thread constructor. |
| 417 | void DoInit(); |
| 418 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 419 | // Perform cleanup; subclasses must call this from the destructor, |
| 420 | // and are not expected to actually hold the lock. |
Danil Chapovalov | 3ab76d9 | 2022-09-23 12:39:21 +0200 | [diff] [blame] | 421 | void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(mutex_); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 422 | |
| 423 | void WakeUpSocketServer(); |
| 424 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 425 | // Same as WrapCurrent except that it never fails as it does not try to |
| 426 | // acquire the synchronization access of the thread. The caller should never |
| 427 | // call Stop() or Join() on this thread. |
| 428 | void SafeWrapCurrent(); |
| 429 | |
| 430 | // Blocks the calling thread until this thread has terminated. |
| 431 | void Join(); |
| 432 | |
| 433 | static void AssertBlockingIsAllowedOnCurrentThread(); |
| 434 | |
| 435 | friend class ScopedDisallowBlockingCalls; |
| 436 | |
| 437 | private: |
Harald Alvestrand | ba69442 | 2021-01-27 21:52:14 +0000 | [diff] [blame] | 438 | static const int kSlowDispatchLoggingThreshold = 50; // 50 ms |
| 439 | |
Danil Chapovalov | 207f853 | 2022-08-24 12:19:46 +0200 | [diff] [blame] | 440 | // Get() will process I/O until: |
Danil Chapovalov | d44e341 | 2022-09-16 17:26:10 +0200 | [diff] [blame] | 441 | // 1) A task is available (returns it) |
| 442 | // 2) cmsWait seconds have elapsed (returns empty task) |
| 443 | // 3) Stop() is called (returns empty task) |
| 444 | absl::AnyInvocable<void() &&> Get(int cmsWait); |
| 445 | void Dispatch(absl::AnyInvocable<void() &&> task); |
Danil Chapovalov | 207f853 | 2022-08-24 12:19:46 +0200 | [diff] [blame] | 446 | |
Karl Wiberg | 3256225 | 2019-02-21 13:38:30 +0100 | [diff] [blame] | 447 | // Sets the per-thread allow-blocking-calls flag and returns the previous |
| 448 | // value. Must be called on this thread. |
| 449 | bool SetAllowBlockingCalls(bool allow); |
| 450 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 451 | #if defined(WEBRTC_WIN) |
| 452 | static DWORD WINAPI PreRun(LPVOID context); |
| 453 | #else |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 454 | static void* PreRun(void* pv); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 455 | #endif |
| 456 | |
| 457 | // ThreadManager calls this instead WrapCurrent() because |
| 458 | // ThreadManager::Instance() cannot be used while ThreadManager is |
| 459 | // being created. |
| 460 | // The method tries to get synchronization rights of the thread on Windows if |
Artem Titov | 96e3b99 | 2021-07-26 16:03:14 +0200 | [diff] [blame] | 461 | // `need_synchronize_access` is true. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 462 | bool WrapCurrentWithThreadManager(ThreadManager* thread_manager, |
| 463 | bool need_synchronize_access); |
| 464 | |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 465 | // Return true if the thread is currently running. |
| 466 | bool IsRunning(); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 467 | |
Tommi | 6866dc7 | 2020-05-15 10:11:56 +0200 | [diff] [blame] | 468 | // Called by the ThreadManager when being set as the current thread. |
| 469 | void EnsureIsCurrentTaskQueue(); |
| 470 | |
| 471 | // Called by the ThreadManager when being unset as the current thread. |
| 472 | void ClearCurrentTaskQueue(); |
| 473 | |
Danil Chapovalov | 3ab76d9 | 2022-09-23 12:39:21 +0200 | [diff] [blame] | 474 | std::queue<absl::AnyInvocable<void() &&>> messages_ RTC_GUARDED_BY(mutex_); |
| 475 | std::priority_queue<DelayedMessage> delayed_messages_ RTC_GUARDED_BY(mutex_); |
| 476 | uint32_t delayed_next_num_ RTC_GUARDED_BY(mutex_); |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 477 | #if RTC_DCHECK_IS_ON |
| 478 | uint32_t blocking_call_count_ RTC_GUARDED_BY(this) = 0; |
| 479 | uint32_t could_be_blocking_call_count_ RTC_GUARDED_BY(this) = 0; |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 480 | std::vector<Thread*> allowed_threads_ RTC_GUARDED_BY(this); |
| 481 | bool invoke_policy_enabled_ RTC_GUARDED_BY(this) = false; |
| 482 | #endif |
Danil Chapovalov | 3ab76d9 | 2022-09-23 12:39:21 +0200 | [diff] [blame] | 483 | mutable webrtc::Mutex mutex_; |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 484 | bool fInitialized_; |
| 485 | bool fDestroyed_; |
| 486 | |
Niels Möller | 7a66900 | 2022-06-27 09:47:02 +0200 | [diff] [blame] | 487 | std::atomic<int> stop_; |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 488 | |
| 489 | // The SocketServer might not be owned by Thread. |
| 490 | SocketServer* const ss_; |
Artem Titov | 96e3b99 | 2021-07-26 16:03:14 +0200 | [diff] [blame] | 491 | // Used if SocketServer ownership lies with `this`. |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 492 | std::unique_ptr<SocketServer> own_ss_; |
| 493 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 494 | std::string name_; |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 495 | |
Jonas Olsson | a4d8737 | 2019-07-05 19:08:33 +0200 | [diff] [blame] | 496 | // TODO(tommi): Add thread checks for proper use of control methods. |
| 497 | // Ideally we should be able to just use PlatformThread. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 498 | |
| 499 | #if defined(WEBRTC_POSIX) |
Tommi | 6cea2b0 | 2017-12-04 18:51:16 +0100 | [diff] [blame] | 500 | pthread_t thread_ = 0; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 501 | #endif |
| 502 | |
| 503 | #if defined(WEBRTC_WIN) |
Tommi | 6cea2b0 | 2017-12-04 18:51:16 +0100 | [diff] [blame] | 504 | HANDLE thread_ = nullptr; |
| 505 | DWORD thread_id_ = 0; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 506 | #endif |
| 507 | |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 508 | // Indicates whether or not ownership of the worker thread lies with |
| 509 | // this instance or not. (i.e. owned_ == !wrapped). |
| 510 | // Must only be modified when the worker thread is not running. |
| 511 | bool owned_ = true; |
| 512 | |
| 513 | // Only touched from the worker thread itself. |
| 514 | bool blocking_calls_allowed_ = true; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 515 | |
Tommi | 6866dc7 | 2020-05-15 10:11:56 +0200 | [diff] [blame] | 516 | std::unique_ptr<TaskQueueBase::CurrentTaskQueueSetter> |
| 517 | task_queue_registration_; |
Danil Chapovalov | 912b3b8 | 2019-11-22 15:52:40 +0100 | [diff] [blame] | 518 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 519 | friend class ThreadManager; |
| 520 | |
Harald Alvestrand | ba69442 | 2021-01-27 21:52:14 +0000 | [diff] [blame] | 521 | int dispatch_warning_ms_ RTC_GUARDED_BY(this) = kSlowDispatchLoggingThreshold; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 522 | }; |
| 523 | |
| 524 | // AutoThread automatically installs itself at construction |
| 525 | // uninstalls at destruction, if a Thread object is |
| 526 | // _not already_ associated with the current OS thread. |
Tomas Gunnarsson | 0fd4c4e | 2020-09-04 16:33:25 +0200 | [diff] [blame] | 527 | // |
| 528 | // NOTE: *** This class should only be used by tests *** |
| 529 | // |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 530 | class AutoThread : public Thread { |
| 531 | public: |
| 532 | AutoThread(); |
| 533 | ~AutoThread() override; |
| 534 | |
Byoungchan Lee | 14af762 | 2022-01-12 05:24:58 +0900 | [diff] [blame] | 535 | AutoThread(const AutoThread&) = delete; |
| 536 | AutoThread& operator=(const AutoThread&) = delete; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 537 | }; |
| 538 | |
| 539 | // AutoSocketServerThread automatically installs itself at |
| 540 | // construction and uninstalls at destruction. If a Thread object is |
| 541 | // already associated with the current OS thread, it is temporarily |
| 542 | // disassociated and restored by the destructor. |
| 543 | |
| 544 | class AutoSocketServerThread : public Thread { |
| 545 | public: |
| 546 | explicit AutoSocketServerThread(SocketServer* ss); |
| 547 | ~AutoSocketServerThread() override; |
| 548 | |
Byoungchan Lee | 14af762 | 2022-01-12 05:24:58 +0900 | [diff] [blame] | 549 | AutoSocketServerThread(const AutoSocketServerThread&) = delete; |
| 550 | AutoSocketServerThread& operator=(const AutoSocketServerThread&) = delete; |
| 551 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 552 | private: |
| 553 | rtc::Thread* old_thread_; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 554 | }; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 555 | } // namespace rtc |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 556 | |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 557 | #endif // RTC_BASE_THREAD_H_ |