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 | #include "rtc_base/thread.h" |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 12 | |
Ali Tofigh | 7fa9057 | 2022-03-17 15:47:49 +0100 | [diff] [blame] | 13 | #include "absl/strings/string_view.h" |
| 14 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 15 | #if defined(WEBRTC_WIN) |
| 16 | #include <comdef.h> |
| 17 | #elif defined(WEBRTC_POSIX) |
| 18 | #include <time.h> |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 19 | #else |
| 20 | #error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined." |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 21 | #endif |
| 22 | |
Artem Titov | 80d02ad | 2018-05-21 12:20:39 +0200 | [diff] [blame] | 23 | #if defined(WEBRTC_WIN) |
| 24 | // Disable warning that we don't care about: |
| 25 | // warning C4722: destructor never returns, potential memory leak |
| 26 | #pragma warning(disable : 4722) |
| 27 | #endif |
| 28 | |
Yves Gerey | 988cc08 | 2018-10-23 12:03:01 +0200 | [diff] [blame] | 29 | #include <stdio.h> |
Jonas Olsson | a4d8737 | 2019-07-05 19:08:33 +0200 | [diff] [blame] | 30 | |
Yves Gerey | 988cc08 | 2018-10-23 12:03:01 +0200 | [diff] [blame] | 31 | #include <utility> |
Yves Gerey | 2e00abc | 2018-10-05 15:39:24 +0200 | [diff] [blame] | 32 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 33 | #include "absl/algorithm/container.h" |
Danil Chapovalov | 4bcf809 | 2022-07-06 19:42:34 +0200 | [diff] [blame] | 34 | #include "absl/cleanup/cleanup.h" |
Artem Titov | d15a575 | 2021-02-10 14:31:24 +0100 | [diff] [blame] | 35 | #include "api/sequence_checker.h" |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 36 | #include "rtc_base/checks.h" |
Markus Handell | 3cb525b | 2020-07-16 16:16:09 +0200 | [diff] [blame] | 37 | #include "rtc_base/deprecated/recursive_critical_section.h" |
Tomas Gunnarsson | 0fd4c4e | 2020-09-04 16:33:25 +0200 | [diff] [blame] | 38 | #include "rtc_base/event.h" |
Mirko Bonadei | e5f4c6b | 2021-01-15 10:41:01 +0100 | [diff] [blame] | 39 | #include "rtc_base/internal/default_socket_server.h" |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 40 | #include "rtc_base/logging.h" |
Steve Anton | 10542f2 | 2019-01-11 09:11:00 -0800 | [diff] [blame] | 41 | #include "rtc_base/null_socket_server.h" |
| 42 | #include "rtc_base/time_utils.h" |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 43 | #include "rtc_base/trace_event.h" |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 44 | |
Kári Tristan Helgason | 62b1345 | 2018-10-12 12:57:49 +0200 | [diff] [blame] | 45 | #if defined(WEBRTC_MAC) |
| 46 | #include "rtc_base/system/cocoa_threading.h" |
Yves Gerey | 988cc08 | 2018-10-23 12:03:01 +0200 | [diff] [blame] | 47 | |
Kári Tristan Helgason | 62b1345 | 2018-10-12 12:57:49 +0200 | [diff] [blame] | 48 | /* |
| 49 | * These are forward-declarations for methods that are part of the |
| 50 | * ObjC runtime. They are declared in the private header objc-internal.h. |
| 51 | * These calls are what clang inserts when using @autoreleasepool in ObjC, |
| 52 | * but here they are used directly in order to keep this file C++. |
| 53 | * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support |
| 54 | */ |
| 55 | extern "C" { |
| 56 | void* objc_autoreleasePoolPush(void); |
| 57 | void objc_autoreleasePoolPop(void* pool); |
| 58 | } |
| 59 | |
| 60 | namespace { |
| 61 | class ScopedAutoReleasePool { |
| 62 | public: |
| 63 | ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {} |
| 64 | ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); } |
| 65 | |
| 66 | private: |
| 67 | void* const pool_; |
| 68 | }; |
| 69 | } // namespace |
| 70 | #endif |
| 71 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 72 | namespace rtc { |
Steve Anton | bcc1a76 | 2019-12-11 11:21:53 -0800 | [diff] [blame] | 73 | namespace { |
| 74 | |
Danil Chapovalov | 4bcf809 | 2022-07-06 19:42:34 +0200 | [diff] [blame] | 75 | struct AnyInvocableMessage final : public MessageData { |
| 76 | explicit AnyInvocableMessage(absl::AnyInvocable<void() &&> task) |
| 77 | : task(std::move(task)) {} |
| 78 | absl::AnyInvocable<void() &&> task; |
| 79 | }; |
| 80 | |
| 81 | class AnyInvocableMessageHandler final : public MessageHandler { |
Steve Anton | bcc1a76 | 2019-12-11 11:21:53 -0800 | [diff] [blame] | 82 | public: |
Steve Anton | bcc1a76 | 2019-12-11 11:21:53 -0800 | [diff] [blame] | 83 | void OnMessage(Message* msg) override { |
Danil Chapovalov | 4bcf809 | 2022-07-06 19:42:34 +0200 | [diff] [blame] | 84 | std::move(static_cast<AnyInvocableMessage*>(msg->pdata)->task)(); |
Steve Anton | bcc1a76 | 2019-12-11 11:21:53 -0800 | [diff] [blame] | 85 | delete msg->pdata; |
| 86 | } |
Steve Anton | bcc1a76 | 2019-12-11 11:21:53 -0800 | [diff] [blame] | 87 | }; |
| 88 | |
Danil Chapovalov | 4bcf809 | 2022-07-06 19:42:34 +0200 | [diff] [blame] | 89 | MessageHandler* GetAnyInvocableMessageHandler() { |
| 90 | static MessageHandler* const handler = new AnyInvocableMessageHandler; |
| 91 | return handler; |
| 92 | } |
| 93 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 94 | class RTC_SCOPED_LOCKABLE MarkProcessingCritScope { |
| 95 | public: |
Markus Handell | 3cb525b | 2020-07-16 16:16:09 +0200 | [diff] [blame] | 96 | MarkProcessingCritScope(const RecursiveCriticalSection* cs, |
| 97 | size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs) |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 98 | : cs_(cs), processing_(processing) { |
| 99 | cs_->Enter(); |
| 100 | *processing_ += 1; |
| 101 | } |
| 102 | |
| 103 | ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() { |
| 104 | *processing_ -= 1; |
| 105 | cs_->Leave(); |
| 106 | } |
| 107 | |
Byoungchan Lee | 14af762 | 2022-01-12 05:24:58 +0900 | [diff] [blame] | 108 | MarkProcessingCritScope(const MarkProcessingCritScope&) = delete; |
| 109 | MarkProcessingCritScope& operator=(const MarkProcessingCritScope&) = delete; |
| 110 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 111 | private: |
Markus Handell | 3cb525b | 2020-07-16 16:16:09 +0200 | [diff] [blame] | 112 | const RecursiveCriticalSection* const cs_; |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 113 | size_t* processing_; |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 114 | }; |
| 115 | |
Steve Anton | bcc1a76 | 2019-12-11 11:21:53 -0800 | [diff] [blame] | 116 | } // namespace |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 117 | |
| 118 | ThreadManager* ThreadManager::Instance() { |
Niels Möller | 14682a3 | 2018-05-24 08:54:25 +0200 | [diff] [blame] | 119 | static ThreadManager* const thread_manager = new ThreadManager(); |
| 120 | return thread_manager; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 121 | } |
| 122 | |
nisse | 7866cfe | 2017-04-26 01:45:31 -0700 | [diff] [blame] | 123 | ThreadManager::~ThreadManager() { |
| 124 | // By above RTC_DEFINE_STATIC_LOCAL. |
Artem Titov | d325196 | 2021-11-15 16:57:07 +0100 | [diff] [blame] | 125 | RTC_DCHECK_NOTREACHED() << "ThreadManager should never be destructed."; |
nisse | 7866cfe | 2017-04-26 01:45:31 -0700 | [diff] [blame] | 126 | } |
| 127 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 128 | // static |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 129 | void ThreadManager::Add(Thread* message_queue) { |
| 130 | return Instance()->AddInternal(message_queue); |
| 131 | } |
| 132 | void ThreadManager::AddInternal(Thread* message_queue) { |
| 133 | CritScope cs(&crit_); |
| 134 | // Prevent changes while the list of message queues is processed. |
| 135 | RTC_DCHECK_EQ(processing_, 0); |
| 136 | message_queues_.push_back(message_queue); |
| 137 | } |
| 138 | |
| 139 | // static |
| 140 | void ThreadManager::Remove(Thread* message_queue) { |
| 141 | return Instance()->RemoveInternal(message_queue); |
| 142 | } |
| 143 | void ThreadManager::RemoveInternal(Thread* message_queue) { |
| 144 | { |
| 145 | CritScope cs(&crit_); |
| 146 | // Prevent changes while the list of message queues is processed. |
| 147 | RTC_DCHECK_EQ(processing_, 0); |
| 148 | std::vector<Thread*>::iterator iter; |
| 149 | iter = absl::c_find(message_queues_, message_queue); |
| 150 | if (iter != message_queues_.end()) { |
| 151 | message_queues_.erase(iter); |
| 152 | } |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 153 | #if RTC_DCHECK_IS_ON |
| 154 | RemoveFromSendGraph(message_queue); |
| 155 | #endif |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 156 | } |
| 157 | } |
| 158 | |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 159 | #if RTC_DCHECK_IS_ON |
| 160 | void ThreadManager::RemoveFromSendGraph(Thread* thread) { |
| 161 | for (auto it = send_graph_.begin(); it != send_graph_.end();) { |
| 162 | if (it->first == thread) { |
| 163 | it = send_graph_.erase(it); |
| 164 | } else { |
| 165 | it->second.erase(thread); |
| 166 | ++it; |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | void ThreadManager::RegisterSendAndCheckForCycles(Thread* source, |
| 172 | Thread* target) { |
Tomas Gunnarsson | 0fd4c4e | 2020-09-04 16:33:25 +0200 | [diff] [blame] | 173 | RTC_DCHECK(source); |
| 174 | RTC_DCHECK(target); |
| 175 | |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 176 | CritScope cs(&crit_); |
| 177 | std::deque<Thread*> all_targets({target}); |
| 178 | // We check the pre-existing who-sends-to-who graph for any path from target |
| 179 | // to source. This loop is guaranteed to terminate because per the send graph |
| 180 | // invariant, there are no cycles in the graph. |
Jianjun Zhu | c33eeab | 2020-05-26 17:43:17 +0800 | [diff] [blame] | 181 | for (size_t i = 0; i < all_targets.size(); i++) { |
| 182 | const auto& targets = send_graph_[all_targets[i]]; |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 183 | all_targets.insert(all_targets.end(), targets.begin(), targets.end()); |
| 184 | } |
| 185 | RTC_CHECK_EQ(absl::c_count(all_targets, source), 0) |
| 186 | << " send loop between " << source->name() << " and " << target->name(); |
| 187 | |
| 188 | // We may now insert source -> target without creating a cycle, since there |
| 189 | // was no path from target to source per the prior CHECK. |
| 190 | send_graph_[source].insert(target); |
| 191 | } |
| 192 | #endif |
| 193 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 194 | // static |
| 195 | void ThreadManager::Clear(MessageHandler* handler) { |
| 196 | return Instance()->ClearInternal(handler); |
| 197 | } |
| 198 | void ThreadManager::ClearInternal(MessageHandler* handler) { |
| 199 | // Deleted objects may cause re-entrant calls to ClearInternal. This is |
| 200 | // allowed as the list of message queues does not change while queues are |
| 201 | // cleared. |
| 202 | MarkProcessingCritScope cs(&crit_, &processing_); |
| 203 | for (Thread* queue : message_queues_) { |
| 204 | queue->Clear(handler); |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // static |
| 209 | void ThreadManager::ProcessAllMessageQueuesForTesting() { |
| 210 | return Instance()->ProcessAllMessageQueuesInternal(); |
| 211 | } |
| 212 | |
| 213 | void ThreadManager::ProcessAllMessageQueuesInternal() { |
| 214 | // This works by posting a delayed message at the current time and waiting |
| 215 | // for it to be dispatched on all queues, which will ensure that all messages |
| 216 | // that came before it were also dispatched. |
Niels Möller | 7a66900 | 2022-06-27 09:47:02 +0200 | [diff] [blame] | 217 | std::atomic<int> queues_not_done(0); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 218 | |
| 219 | // This class is used so that whether the posted message is processed, or the |
| 220 | // message queue is simply cleared, queues_not_done gets decremented. |
| 221 | class ScopedIncrement : public MessageData { |
| 222 | public: |
Niels Möller | 7a66900 | 2022-06-27 09:47:02 +0200 | [diff] [blame] | 223 | ScopedIncrement(std::atomic<int>* value) : value_(value) { |
| 224 | value_->fetch_add(1); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 225 | } |
Niels Möller | 7a66900 | 2022-06-27 09:47:02 +0200 | [diff] [blame] | 226 | ~ScopedIncrement() override { value_->fetch_sub(1); } |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 227 | |
| 228 | private: |
Niels Möller | 7a66900 | 2022-06-27 09:47:02 +0200 | [diff] [blame] | 229 | std::atomic<int>* value_; |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 230 | }; |
| 231 | |
| 232 | { |
| 233 | MarkProcessingCritScope cs(&crit_, &processing_); |
| 234 | for (Thread* queue : message_queues_) { |
| 235 | if (!queue->IsProcessingMessagesForTesting()) { |
| 236 | // If the queue is not processing messages, it can |
| 237 | // be ignored. If we tried to post a message to it, it would be dropped |
| 238 | // or ignored. |
| 239 | continue; |
| 240 | } |
| 241 | queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE, |
| 242 | new ScopedIncrement(&queues_not_done)); |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | rtc::Thread* current = rtc::Thread::Current(); |
| 247 | // Note: One of the message queues may have been on this thread, which is |
| 248 | // why we can't synchronously wait for queues_not_done to go to 0; we need |
| 249 | // to process messages as well. |
Niels Möller | 7a66900 | 2022-06-27 09:47:02 +0200 | [diff] [blame] | 250 | while (queues_not_done.load() > 0) { |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 251 | if (current) { |
| 252 | current->ProcessMessages(0); |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | // static |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 258 | Thread* Thread::Current() { |
nisse | 7866cfe | 2017-04-26 01:45:31 -0700 | [diff] [blame] | 259 | ThreadManager* manager = ThreadManager::Instance(); |
| 260 | Thread* thread = manager->CurrentThread(); |
| 261 | |
nisse | 7866cfe | 2017-04-26 01:45:31 -0700 | [diff] [blame] | 262 | return thread; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 263 | } |
| 264 | |
| 265 | #if defined(WEBRTC_POSIX) |
Niels Möller | 98d26df | 2022-02-07 10:35:29 +0100 | [diff] [blame] | 266 | ThreadManager::ThreadManager() { |
Kári Tristan Helgason | 62b1345 | 2018-10-12 12:57:49 +0200 | [diff] [blame] | 267 | #if defined(WEBRTC_MAC) |
| 268 | InitCocoaMultiThreading(); |
| 269 | #endif |
deadbeef | 37f5ecf | 2017-02-27 14:06:41 -0800 | [diff] [blame] | 270 | pthread_key_create(&key_, nullptr); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 271 | } |
| 272 | |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 273 | Thread* ThreadManager::CurrentThread() { |
| 274 | return static_cast<Thread*>(pthread_getspecific(key_)); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 275 | } |
| 276 | |
Sebastian Jansson | 178a685 | 2020-01-14 11:12:26 +0100 | [diff] [blame] | 277 | void ThreadManager::SetCurrentThreadInternal(Thread* thread) { |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 278 | pthread_setspecific(key_, thread); |
| 279 | } |
| 280 | #endif |
| 281 | |
| 282 | #if defined(WEBRTC_WIN) |
Niels Möller | 98d26df | 2022-02-07 10:35:29 +0100 | [diff] [blame] | 283 | ThreadManager::ThreadManager() : key_(TlsAlloc()) {} |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 284 | |
| 285 | Thread* ThreadManager::CurrentThread() { |
| 286 | return static_cast<Thread*>(TlsGetValue(key_)); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 287 | } |
| 288 | |
Sebastian Jansson | 178a685 | 2020-01-14 11:12:26 +0100 | [diff] [blame] | 289 | void ThreadManager::SetCurrentThreadInternal(Thread* thread) { |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 290 | TlsSetValue(key_, thread); |
| 291 | } |
| 292 | #endif |
| 293 | |
Sebastian Jansson | 178a685 | 2020-01-14 11:12:26 +0100 | [diff] [blame] | 294 | void ThreadManager::SetCurrentThread(Thread* thread) { |
| 295 | #if RTC_DLOG_IS_ON |
| 296 | if (CurrentThread() && thread) { |
| 297 | RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?"; |
| 298 | } |
| 299 | #endif // RTC_DLOG_IS_ON |
Tommi | 6866dc7 | 2020-05-15 10:11:56 +0200 | [diff] [blame] | 300 | |
| 301 | if (thread) { |
| 302 | thread->EnsureIsCurrentTaskQueue(); |
| 303 | } else { |
| 304 | Thread* current = CurrentThread(); |
| 305 | if (current) { |
| 306 | // The current thread is being cleared, e.g. as a result of |
| 307 | // UnwrapCurrent() being called or when a thread is being stopped |
| 308 | // (see PreRun()). This signals that the Thread instance is being detached |
| 309 | // from the thread, which also means that TaskQueue::Current() must not |
| 310 | // return a pointer to the Thread instance. |
| 311 | current->ClearCurrentTaskQueue(); |
| 312 | } |
| 313 | } |
| 314 | |
Sebastian Jansson | 178a685 | 2020-01-14 11:12:26 +0100 | [diff] [blame] | 315 | SetCurrentThreadInternal(thread); |
| 316 | } |
| 317 | |
| 318 | void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) { |
| 319 | SetCurrentThreadInternal(thread); |
| 320 | } |
| 321 | |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 322 | Thread* ThreadManager::WrapCurrentThread() { |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 323 | Thread* result = CurrentThread(); |
deadbeef | 37f5ecf | 2017-02-27 14:06:41 -0800 | [diff] [blame] | 324 | if (nullptr == result) { |
Mirko Bonadei | e5f4c6b | 2021-01-15 10:41:01 +0100 | [diff] [blame] | 325 | result = new Thread(CreateDefaultSocketServer()); |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 326 | result->WrapCurrentWithThreadManager(this, true); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 327 | } |
| 328 | return result; |
| 329 | } |
| 330 | |
| 331 | void ThreadManager::UnwrapCurrentThread() { |
| 332 | Thread* t = CurrentThread(); |
| 333 | if (t && !(t->IsOwned())) { |
| 334 | t->UnwrapCurrent(); |
| 335 | delete t; |
| 336 | } |
| 337 | } |
| 338 | |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 339 | Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls() |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 340 | : thread_(Thread::Current()), |
| 341 | previous_state_(thread_->SetAllowBlockingCalls(false)) {} |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 342 | |
| 343 | Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() { |
nisse | ede5da4 | 2017-01-12 05:15:36 -0800 | [diff] [blame] | 344 | RTC_DCHECK(thread_->IsCurrent()); |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 345 | thread_->SetAllowBlockingCalls(previous_state_); |
| 346 | } |
| 347 | |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 348 | #if RTC_DCHECK_IS_ON |
| 349 | Thread::ScopedCountBlockingCalls::ScopedCountBlockingCalls( |
| 350 | std::function<void(uint32_t, uint32_t)> callback) |
| 351 | : thread_(Thread::Current()), |
| 352 | base_blocking_call_count_(thread_->GetBlockingCallCount()), |
| 353 | base_could_be_blocking_call_count_( |
| 354 | thread_->GetCouldBeBlockingCallCount()), |
| 355 | result_callback_(std::move(callback)) {} |
| 356 | |
| 357 | Thread::ScopedCountBlockingCalls::~ScopedCountBlockingCalls() { |
Tomas Gunnarsson | 89f3dd5 | 2021-04-14 12:54:10 +0200 | [diff] [blame] | 358 | if (GetTotalBlockedCallCount() >= min_blocking_calls_for_callback_) { |
| 359 | result_callback_(GetBlockingCallCount(), GetCouldBeBlockingCallCount()); |
| 360 | } |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 361 | } |
| 362 | |
| 363 | uint32_t Thread::ScopedCountBlockingCalls::GetBlockingCallCount() const { |
| 364 | return thread_->GetBlockingCallCount() - base_blocking_call_count_; |
| 365 | } |
| 366 | |
| 367 | uint32_t Thread::ScopedCountBlockingCalls::GetCouldBeBlockingCallCount() const { |
| 368 | return thread_->GetCouldBeBlockingCallCount() - |
| 369 | base_could_be_blocking_call_count_; |
| 370 | } |
| 371 | |
| 372 | uint32_t Thread::ScopedCountBlockingCalls::GetTotalBlockedCallCount() const { |
| 373 | return GetBlockingCallCount() + GetCouldBeBlockingCallCount(); |
| 374 | } |
| 375 | #endif |
| 376 | |
Taylor Brandstetter | 0867260 | 2018-03-02 15:20:33 -0800 | [diff] [blame] | 377 | Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {} |
danilchap | bebf54c | 2016-04-28 01:32:48 -0700 | [diff] [blame] | 378 | |
| 379 | Thread::Thread(std::unique_ptr<SocketServer> ss) |
Taylor Brandstetter | 0867260 | 2018-03-02 15:20:33 -0800 | [diff] [blame] | 380 | : Thread(std::move(ss), /*do_init=*/true) {} |
| 381 | |
| 382 | Thread::Thread(SocketServer* ss, bool do_init) |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 383 | : fPeekKeep_(false), |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 384 | delayed_next_num_(0), |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 385 | fInitialized_(false), |
| 386 | fDestroyed_(false), |
| 387 | stop_(0), |
| 388 | ss_(ss) { |
| 389 | RTC_DCHECK(ss); |
| 390 | ss_->SetMessageQueue(this); |
Taylor Brandstetter | 0867260 | 2018-03-02 15:20:33 -0800 | [diff] [blame] | 391 | SetName("Thread", this); // default name |
| 392 | if (do_init) { |
| 393 | DoInit(); |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init) |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 398 | : Thread(ss.get(), do_init) { |
| 399 | own_ss_ = std::move(ss); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 400 | } |
| 401 | |
| 402 | Thread::~Thread() { |
| 403 | Stop(); |
jbauch | 25d1f28 | 2016-02-05 00:25:02 -0800 | [diff] [blame] | 404 | DoDestroy(); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 405 | } |
| 406 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 407 | void Thread::DoInit() { |
| 408 | if (fInitialized_) { |
| 409 | return; |
| 410 | } |
| 411 | |
| 412 | fInitialized_ = true; |
| 413 | ThreadManager::Add(this); |
| 414 | } |
| 415 | |
| 416 | void Thread::DoDestroy() { |
| 417 | if (fDestroyed_) { |
| 418 | return; |
| 419 | } |
| 420 | |
| 421 | fDestroyed_ = true; |
| 422 | // The signal is done from here to ensure |
| 423 | // that it always gets called when the queue |
| 424 | // is going away. |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 425 | if (ss_) { |
| 426 | ss_->SetMessageQueue(nullptr); |
| 427 | } |
Niels Möller | 9bd2457 | 2021-04-19 12:18:27 +0200 | [diff] [blame] | 428 | ThreadManager::Remove(this); |
| 429 | ClearInternal(nullptr, MQID_ANY, nullptr); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 430 | } |
| 431 | |
| 432 | SocketServer* Thread::socketserver() { |
| 433 | return ss_; |
| 434 | } |
| 435 | |
| 436 | void Thread::WakeUpSocketServer() { |
| 437 | ss_->WakeUp(); |
| 438 | } |
| 439 | |
| 440 | void Thread::Quit() { |
Niels Möller | 7a66900 | 2022-06-27 09:47:02 +0200 | [diff] [blame] | 441 | stop_.store(1, std::memory_order_release); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 442 | WakeUpSocketServer(); |
| 443 | } |
| 444 | |
| 445 | bool Thread::IsQuitting() { |
Niels Möller | 7a66900 | 2022-06-27 09:47:02 +0200 | [diff] [blame] | 446 | return stop_.load(std::memory_order_acquire) != 0; |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 447 | } |
| 448 | |
| 449 | void Thread::Restart() { |
Niels Möller | 7a66900 | 2022-06-27 09:47:02 +0200 | [diff] [blame] | 450 | stop_.store(0, std::memory_order_release); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 451 | } |
| 452 | |
| 453 | bool Thread::Peek(Message* pmsg, int cmsWait) { |
| 454 | if (fPeekKeep_) { |
| 455 | *pmsg = msgPeek_; |
| 456 | return true; |
| 457 | } |
| 458 | if (!Get(pmsg, cmsWait)) |
| 459 | return false; |
| 460 | msgPeek_ = *pmsg; |
| 461 | fPeekKeep_ = true; |
| 462 | return true; |
| 463 | } |
| 464 | |
| 465 | bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) { |
| 466 | // Return and clear peek if present |
| 467 | // Always return the peek if it exists so there is Peek/Get symmetry |
| 468 | |
| 469 | if (fPeekKeep_) { |
| 470 | *pmsg = msgPeek_; |
| 471 | fPeekKeep_ = false; |
| 472 | return true; |
| 473 | } |
| 474 | |
| 475 | // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch |
| 476 | |
| 477 | int64_t cmsTotal = cmsWait; |
| 478 | int64_t cmsElapsed = 0; |
| 479 | int64_t msStart = TimeMillis(); |
| 480 | int64_t msCurrent = msStart; |
| 481 | while (true) { |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 482 | // Check for posted events |
| 483 | int64_t cmsDelayNext = kForever; |
| 484 | bool first_pass = true; |
| 485 | while (true) { |
| 486 | // All queue operations need to be locked, but nothing else in this loop |
| 487 | // (specifically handling disposed message) can happen inside the crit. |
| 488 | // Otherwise, disposed MessageHandlers will cause deadlocks. |
| 489 | { |
| 490 | CritScope cs(&crit_); |
| 491 | // On the first pass, check for delayed messages that have been |
| 492 | // triggered and calculate the next trigger time. |
| 493 | if (first_pass) { |
| 494 | first_pass = false; |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 495 | while (!delayed_messages_.empty()) { |
| 496 | if (msCurrent < delayed_messages_.top().run_time_ms_) { |
| 497 | cmsDelayNext = |
| 498 | TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 499 | break; |
| 500 | } |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 501 | messages_.push_back(delayed_messages_.top().msg_); |
| 502 | delayed_messages_.pop(); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 503 | } |
| 504 | } |
| 505 | // Pull a message off the message queue, if available. |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 506 | if (messages_.empty()) { |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 507 | break; |
| 508 | } else { |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 509 | *pmsg = messages_.front(); |
| 510 | messages_.pop_front(); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 511 | } |
| 512 | } // crit_ is released here. |
| 513 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 514 | // If this was a dispose message, delete it and skip it. |
| 515 | if (MQID_DISPOSE == pmsg->message_id) { |
| 516 | RTC_DCHECK(nullptr == pmsg->phandler); |
| 517 | delete pmsg->pdata; |
| 518 | *pmsg = Message(); |
| 519 | continue; |
| 520 | } |
| 521 | return true; |
| 522 | } |
| 523 | |
| 524 | if (IsQuitting()) |
| 525 | break; |
| 526 | |
| 527 | // Which is shorter, the delay wait or the asked wait? |
| 528 | |
| 529 | int64_t cmsNext; |
| 530 | if (cmsWait == kForever) { |
| 531 | cmsNext = cmsDelayNext; |
| 532 | } else { |
| 533 | cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed); |
| 534 | if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext)) |
| 535 | cmsNext = cmsDelayNext; |
| 536 | } |
| 537 | |
| 538 | { |
| 539 | // Wait and multiplex in the meantime |
| 540 | if (!ss_->Wait(static_cast<int>(cmsNext), process_io)) |
| 541 | return false; |
| 542 | } |
| 543 | |
| 544 | // If the specified timeout expired, return |
| 545 | |
| 546 | msCurrent = TimeMillis(); |
| 547 | cmsElapsed = TimeDiff(msCurrent, msStart); |
| 548 | if (cmsWait != kForever) { |
| 549 | if (cmsElapsed >= cmsWait) |
| 550 | return false; |
| 551 | } |
| 552 | } |
| 553 | return false; |
| 554 | } |
| 555 | |
| 556 | void Thread::Post(const Location& posted_from, |
| 557 | MessageHandler* phandler, |
| 558 | uint32_t id, |
| 559 | MessageData* pdata, |
| 560 | bool time_sensitive) { |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 561 | RTC_DCHECK(!time_sensitive); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 562 | if (IsQuitting()) { |
| 563 | delete pdata; |
| 564 | return; |
| 565 | } |
| 566 | |
| 567 | // Keep thread safe |
| 568 | // Add the message to the end of the queue |
| 569 | // Signal for the multiplexer to return |
| 570 | |
| 571 | { |
| 572 | CritScope cs(&crit_); |
| 573 | Message msg; |
| 574 | msg.posted_from = posted_from; |
| 575 | msg.phandler = phandler; |
| 576 | msg.message_id = id; |
| 577 | msg.pdata = pdata; |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 578 | messages_.push_back(msg); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 579 | } |
| 580 | WakeUpSocketServer(); |
| 581 | } |
| 582 | |
| 583 | void Thread::PostDelayed(const Location& posted_from, |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 584 | int delay_ms, |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 585 | MessageHandler* phandler, |
| 586 | uint32_t id, |
| 587 | MessageData* pdata) { |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 588 | return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id, |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 589 | pdata); |
| 590 | } |
| 591 | |
| 592 | void Thread::PostAt(const Location& posted_from, |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 593 | int64_t run_at_ms, |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 594 | MessageHandler* phandler, |
| 595 | uint32_t id, |
| 596 | MessageData* pdata) { |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 597 | return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id, |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 598 | pdata); |
| 599 | } |
| 600 | |
| 601 | void Thread::DoDelayPost(const Location& posted_from, |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 602 | int64_t delay_ms, |
| 603 | int64_t run_at_ms, |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 604 | MessageHandler* phandler, |
| 605 | uint32_t id, |
| 606 | MessageData* pdata) { |
| 607 | if (IsQuitting()) { |
| 608 | delete pdata; |
| 609 | return; |
| 610 | } |
| 611 | |
| 612 | // Keep thread safe |
| 613 | // Add to the priority queue. Gets sorted soonest first. |
| 614 | // Signal for the multiplexer to return. |
| 615 | |
| 616 | { |
| 617 | CritScope cs(&crit_); |
| 618 | Message msg; |
| 619 | msg.posted_from = posted_from; |
| 620 | msg.phandler = phandler; |
| 621 | msg.message_id = id; |
| 622 | msg.pdata = pdata; |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 623 | DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg); |
| 624 | delayed_messages_.push(delayed); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 625 | // If this message queue processes 1 message every millisecond for 50 days, |
| 626 | // we will wrap this number. Even then, only messages with identical times |
| 627 | // will be misordered, and then only briefly. This is probably ok. |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 628 | ++delayed_next_num_; |
| 629 | RTC_DCHECK_NE(0, delayed_next_num_); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 630 | } |
| 631 | WakeUpSocketServer(); |
| 632 | } |
| 633 | |
| 634 | int Thread::GetDelay() { |
| 635 | CritScope cs(&crit_); |
| 636 | |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 637 | if (!messages_.empty()) |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 638 | return 0; |
| 639 | |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 640 | if (!delayed_messages_.empty()) { |
| 641 | int delay = TimeUntil(delayed_messages_.top().run_time_ms_); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 642 | if (delay < 0) |
| 643 | delay = 0; |
| 644 | return delay; |
| 645 | } |
| 646 | |
| 647 | return kForever; |
| 648 | } |
| 649 | |
| 650 | void Thread::ClearInternal(MessageHandler* phandler, |
| 651 | uint32_t id, |
| 652 | MessageList* removed) { |
| 653 | // Remove messages with phandler |
| 654 | |
| 655 | if (fPeekKeep_ && msgPeek_.Match(phandler, id)) { |
| 656 | if (removed) { |
| 657 | removed->push_back(msgPeek_); |
| 658 | } else { |
| 659 | delete msgPeek_.pdata; |
| 660 | } |
| 661 | fPeekKeep_ = false; |
| 662 | } |
| 663 | |
| 664 | // Remove from ordered message queue |
| 665 | |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 666 | for (auto it = messages_.begin(); it != messages_.end();) { |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 667 | if (it->Match(phandler, id)) { |
| 668 | if (removed) { |
| 669 | removed->push_back(*it); |
| 670 | } else { |
| 671 | delete it->pdata; |
| 672 | } |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 673 | it = messages_.erase(it); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 674 | } else { |
| 675 | ++it; |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | // Remove from priority queue. Not directly iterable, so use this approach |
| 680 | |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 681 | auto new_end = delayed_messages_.container().begin(); |
| 682 | for (auto it = new_end; it != delayed_messages_.container().end(); ++it) { |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 683 | if (it->msg_.Match(phandler, id)) { |
| 684 | if (removed) { |
| 685 | removed->push_back(it->msg_); |
| 686 | } else { |
| 687 | delete it->msg_.pdata; |
| 688 | } |
| 689 | } else { |
| 690 | *new_end++ = *it; |
| 691 | } |
| 692 | } |
Sebastian Jansson | 61380c0 | 2020-01-17 14:46:08 +0100 | [diff] [blame] | 693 | delayed_messages_.container().erase(new_end, |
| 694 | delayed_messages_.container().end()); |
| 695 | delayed_messages_.reheap(); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 696 | } |
| 697 | |
| 698 | void Thread::Dispatch(Message* pmsg) { |
| 699 | TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file", |
| 700 | pmsg->posted_from.file_name(), "src_func", |
| 701 | pmsg->posted_from.function_name()); |
Harald Alvestrand | ba69442 | 2021-01-27 21:52:14 +0000 | [diff] [blame] | 702 | RTC_DCHECK_RUN_ON(this); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 703 | int64_t start_time = TimeMillis(); |
| 704 | pmsg->phandler->OnMessage(pmsg); |
| 705 | int64_t end_time = TimeMillis(); |
| 706 | int64_t diff = TimeDiff(end_time, start_time); |
Harald Alvestrand | ba69442 | 2021-01-27 21:52:14 +0000 | [diff] [blame] | 707 | if (diff >= dispatch_warning_ms_) { |
| 708 | RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 709 | << "ms to dispatch. Posted from: " |
| 710 | << pmsg->posted_from.ToString(); |
Harald Alvestrand | ba69442 | 2021-01-27 21:52:14 +0000 | [diff] [blame] | 711 | // To avoid log spew, move the warning limit to only give warning |
| 712 | // for delays that are larger than the one observed. |
| 713 | dispatch_warning_ms_ = diff + 1; |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 714 | } |
| 715 | } |
| 716 | |
nisse | 7866cfe | 2017-04-26 01:45:31 -0700 | [diff] [blame] | 717 | bool Thread::IsCurrent() const { |
| 718 | return ThreadManager::Instance()->CurrentThread() == this; |
| 719 | } |
| 720 | |
danilchap | bebf54c | 2016-04-28 01:32:48 -0700 | [diff] [blame] | 721 | std::unique_ptr<Thread> Thread::CreateWithSocketServer() { |
Mirko Bonadei | e5f4c6b | 2021-01-15 10:41:01 +0100 | [diff] [blame] | 722 | return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer())); |
danilchap | bebf54c | 2016-04-28 01:32:48 -0700 | [diff] [blame] | 723 | } |
| 724 | |
| 725 | std::unique_ptr<Thread> Thread::Create() { |
| 726 | return std::unique_ptr<Thread>( |
| 727 | new Thread(std::unique_ptr<SocketServer>(new NullSocketServer()))); |
| 728 | } |
| 729 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 730 | bool Thread::SleepMs(int milliseconds) { |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 731 | AssertBlockingIsAllowedOnCurrentThread(); |
| 732 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 733 | #if defined(WEBRTC_WIN) |
| 734 | ::Sleep(milliseconds); |
| 735 | return true; |
| 736 | #else |
| 737 | // POSIX has both a usleep() and a nanosleep(), but the former is deprecated, |
| 738 | // so we use nanosleep() even though it has greater precision than necessary. |
| 739 | struct timespec ts; |
| 740 | ts.tv_sec = milliseconds / 1000; |
| 741 | ts.tv_nsec = (milliseconds % 1000) * 1000000; |
deadbeef | 37f5ecf | 2017-02-27 14:06:41 -0800 | [diff] [blame] | 742 | int ret = nanosleep(&ts, nullptr); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 743 | if (ret != 0) { |
Mirko Bonadei | 675513b | 2017-11-09 11:09:25 +0100 | [diff] [blame] | 744 | RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early"; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 745 | return false; |
| 746 | } |
| 747 | return true; |
| 748 | #endif |
| 749 | } |
| 750 | |
Ali Tofigh | 7fa9057 | 2022-03-17 15:47:49 +0100 | [diff] [blame] | 751 | bool Thread::SetName(absl::string_view name, const void* obj) { |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 752 | RTC_DCHECK(!IsRunning()); |
| 753 | |
Ali Tofigh | 7fa9057 | 2022-03-17 15:47:49 +0100 | [diff] [blame] | 754 | name_ = std::string(name); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 755 | if (obj) { |
Niels Möller | aba0633 | 2018-10-16 15:14:15 +0200 | [diff] [blame] | 756 | // The %p specifier typically produce at most 16 hex digits, possibly with a |
| 757 | // 0x prefix. But format is implementation defined, so add some margin. |
| 758 | char buf[30]; |
| 759 | snprintf(buf, sizeof(buf), " 0x%p", obj); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 760 | name_ += buf; |
| 761 | } |
| 762 | return true; |
| 763 | } |
| 764 | |
Harald Alvestrand | ba69442 | 2021-01-27 21:52:14 +0000 | [diff] [blame] | 765 | void Thread::SetDispatchWarningMs(int deadline) { |
| 766 | if (!IsCurrent()) { |
Danil Chapovalov | 4bcf809 | 2022-07-06 19:42:34 +0200 | [diff] [blame] | 767 | PostTask([this, deadline]() { SetDispatchWarningMs(deadline); }); |
Harald Alvestrand | ba69442 | 2021-01-27 21:52:14 +0000 | [diff] [blame] | 768 | return; |
| 769 | } |
| 770 | RTC_DCHECK_RUN_ON(this); |
| 771 | dispatch_warning_ms_ = deadline; |
| 772 | } |
| 773 | |
Niels Möller | d2e5013 | 2019-06-11 09:24:14 +0200 | [diff] [blame] | 774 | bool Thread::Start() { |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 775 | RTC_DCHECK(!IsRunning()); |
| 776 | |
| 777 | if (IsRunning()) |
| 778 | return false; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 779 | |
André Susano Pinto | 02a5797 | 2016-07-22 13:30:05 +0200 | [diff] [blame] | 780 | Restart(); // reset IsQuitting() if the thread is being restarted |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 781 | |
| 782 | // Make sure that ThreadManager is created on the main thread before |
| 783 | // we start a new thread. |
| 784 | ThreadManager::Instance(); |
| 785 | |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 786 | owned_ = true; |
| 787 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 788 | #if defined(WEBRTC_WIN) |
Niels Möller | d2e5013 | 2019-06-11 09:24:14 +0200 | [diff] [blame] | 789 | thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_); |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 790 | if (!thread_) { |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 791 | return false; |
| 792 | } |
| 793 | #elif defined(WEBRTC_POSIX) |
| 794 | pthread_attr_t attr; |
| 795 | pthread_attr_init(&attr); |
| 796 | |
Niels Möller | d2e5013 | 2019-06-11 09:24:14 +0200 | [diff] [blame] | 797 | int error_code = pthread_create(&thread_, &attr, PreRun, this); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 798 | if (0 != error_code) { |
Mirko Bonadei | 675513b | 2017-11-09 11:09:25 +0100 | [diff] [blame] | 799 | RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code; |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 800 | thread_ = 0; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 801 | return false; |
| 802 | } |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 803 | RTC_DCHECK(thread_); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 804 | #endif |
| 805 | return true; |
| 806 | } |
| 807 | |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 808 | bool Thread::WrapCurrent() { |
| 809 | return WrapCurrentWithThreadManager(ThreadManager::Instance(), true); |
| 810 | } |
| 811 | |
| 812 | void Thread::UnwrapCurrent() { |
| 813 | // Clears the platform-specific thread-specific storage. |
deadbeef | 37f5ecf | 2017-02-27 14:06:41 -0800 | [diff] [blame] | 814 | ThreadManager::Instance()->SetCurrentThread(nullptr); |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 815 | #if defined(WEBRTC_WIN) |
deadbeef | 37f5ecf | 2017-02-27 14:06:41 -0800 | [diff] [blame] | 816 | if (thread_ != nullptr) { |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 817 | if (!CloseHandle(thread_)) { |
Mirko Bonadei | 675513b | 2017-11-09 11:09:25 +0100 | [diff] [blame] | 818 | RTC_LOG_GLE(LS_ERROR) |
| 819 | << "When unwrapping thread, failed to close handle."; |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 820 | } |
deadbeef | 37f5ecf | 2017-02-27 14:06:41 -0800 | [diff] [blame] | 821 | thread_ = nullptr; |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 822 | thread_id_ = 0; |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 823 | } |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 824 | #elif defined(WEBRTC_POSIX) |
| 825 | thread_ = 0; |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 826 | #endif |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 827 | } |
| 828 | |
| 829 | void Thread::SafeWrapCurrent() { |
| 830 | WrapCurrentWithThreadManager(ThreadManager::Instance(), false); |
| 831 | } |
| 832 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 833 | void Thread::Join() { |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 834 | if (!IsRunning()) |
| 835 | return; |
| 836 | |
| 837 | RTC_DCHECK(!IsCurrent()); |
| 838 | if (Current() && !Current()->blocking_calls_allowed_) { |
| 839 | RTC_LOG(LS_WARNING) << "Waiting for the thread to join, " |
Jonas Olsson | b2b2031 | 2020-01-14 12:11:31 +0100 | [diff] [blame] | 840 | "but blocking calls have been disallowed"; |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 841 | } |
jiayl@webrtc.org | 1fd362c | 2014-09-26 16:57:07 +0000 | [diff] [blame] | 842 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 843 | #if defined(WEBRTC_WIN) |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 844 | RTC_DCHECK(thread_ != nullptr); |
| 845 | WaitForSingleObject(thread_, INFINITE); |
| 846 | CloseHandle(thread_); |
| 847 | thread_ = nullptr; |
| 848 | thread_id_ = 0; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 849 | #elif defined(WEBRTC_POSIX) |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 850 | pthread_join(thread_, nullptr); |
| 851 | thread_ = 0; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 852 | #endif |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 853 | } |
| 854 | |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 855 | bool Thread::SetAllowBlockingCalls(bool allow) { |
nisse | ede5da4 | 2017-01-12 05:15:36 -0800 | [diff] [blame] | 856 | RTC_DCHECK(IsCurrent()); |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 857 | bool previous = blocking_calls_allowed_; |
| 858 | blocking_calls_allowed_ = allow; |
| 859 | return previous; |
| 860 | } |
| 861 | |
| 862 | // static |
| 863 | void Thread::AssertBlockingIsAllowedOnCurrentThread() { |
tfarina | a41ab93 | 2015-10-30 16:08:48 -0700 | [diff] [blame] | 864 | #if !defined(NDEBUG) |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 865 | Thread* current = Thread::Current(); |
nisse | ede5da4 | 2017-01-12 05:15:36 -0800 | [diff] [blame] | 866 | RTC_DCHECK(!current || current->blocking_calls_allowed_); |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 867 | #endif |
| 868 | } |
| 869 | |
deadbeef | dc20e26 | 2017-01-31 15:10:44 -0800 | [diff] [blame] | 870 | // static |
| 871 | #if defined(WEBRTC_WIN) |
| 872 | DWORD WINAPI Thread::PreRun(LPVOID pv) { |
| 873 | #else |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 874 | void* Thread::PreRun(void* pv) { |
deadbeef | dc20e26 | 2017-01-31 15:10:44 -0800 | [diff] [blame] | 875 | #endif |
Niels Möller | d2e5013 | 2019-06-11 09:24:14 +0200 | [diff] [blame] | 876 | Thread* thread = static_cast<Thread*>(pv); |
| 877 | ThreadManager::Instance()->SetCurrentThread(thread); |
| 878 | rtc::SetCurrentThreadName(thread->name_.c_str()); |
Kári Tristan Helgason | 62b1345 | 2018-10-12 12:57:49 +0200 | [diff] [blame] | 879 | #if defined(WEBRTC_MAC) |
| 880 | ScopedAutoReleasePool pool; |
| 881 | #endif |
Niels Möller | d2e5013 | 2019-06-11 09:24:14 +0200 | [diff] [blame] | 882 | thread->Run(); |
| 883 | |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 884 | ThreadManager::Instance()->SetCurrentThread(nullptr); |
kthelgason | de6adbe | 2017-02-22 00:42:11 -0800 | [diff] [blame] | 885 | #ifdef WEBRTC_WIN |
| 886 | return 0; |
| 887 | #else |
| 888 | return nullptr; |
| 889 | #endif |
Jonas Olsson | a4d8737 | 2019-07-05 19:08:33 +0200 | [diff] [blame] | 890 | } // namespace rtc |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 891 | |
| 892 | void Thread::Run() { |
| 893 | ProcessMessages(kForever); |
| 894 | } |
| 895 | |
| 896 | bool Thread::IsOwned() { |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 897 | RTC_DCHECK(IsRunning()); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 898 | return owned_; |
| 899 | } |
| 900 | |
| 901 | void Thread::Stop() { |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 902 | Thread::Quit(); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 903 | Join(); |
| 904 | } |
| 905 | |
Taylor Brandstetter | 5d97a9a | 2016-06-10 14:17:27 -0700 | [diff] [blame] | 906 | void Thread::Send(const Location& posted_from, |
| 907 | MessageHandler* phandler, |
| 908 | uint32_t id, |
| 909 | MessageData* pdata) { |
Sebastian Jansson | 5d9b964 | 2020-01-17 13:10:54 +0100 | [diff] [blame] | 910 | RTC_DCHECK(!IsQuitting()); |
André Susano Pinto | 02a5797 | 2016-07-22 13:30:05 +0200 | [diff] [blame] | 911 | if (IsQuitting()) |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 912 | return; |
| 913 | |
| 914 | // Sent messages are sent to the MessageHandler directly, in the context |
| 915 | // of "thread", like Win32 SendMessage. If in the right context, |
| 916 | // call the handler directly. |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 917 | Message msg; |
Taylor Brandstetter | 5d97a9a | 2016-06-10 14:17:27 -0700 | [diff] [blame] | 918 | msg.posted_from = posted_from; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 919 | msg.phandler = phandler; |
| 920 | msg.message_id = id; |
| 921 | msg.pdata = pdata; |
| 922 | if (IsCurrent()) { |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 923 | #if RTC_DCHECK_IS_ON |
Artem Titov | 1573716 | 2021-05-25 11:17:07 +0200 | [diff] [blame] | 924 | RTC_DCHECK(this->IsInvokeToThreadAllowed(this)); |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 925 | RTC_DCHECK_RUN_ON(this); |
| 926 | could_be_blocking_call_count_++; |
| 927 | #endif |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 928 | msg.phandler->OnMessage(&msg); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 929 | return; |
| 930 | } |
| 931 | |
jiayl@webrtc.org | 3987b6d | 2014-09-24 17:14:05 +0000 | [diff] [blame] | 932 | AssertBlockingIsAllowedOnCurrentThread(); |
| 933 | |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 934 | Thread* current_thread = Thread::Current(); |
Tomas Gunnarsson | 0fd4c4e | 2020-09-04 16:33:25 +0200 | [diff] [blame] | 935 | |
Sebastian Jansson | da7267a | 2020-03-03 10:48:05 +0100 | [diff] [blame] | 936 | #if RTC_DCHECK_IS_ON |
Tomas Gunnarsson | 0fd4c4e | 2020-09-04 16:33:25 +0200 | [diff] [blame] | 937 | if (current_thread) { |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 938 | RTC_DCHECK_RUN_ON(current_thread); |
| 939 | current_thread->blocking_call_count_++; |
Tomas Gunnarsson | 0fd4c4e | 2020-09-04 16:33:25 +0200 | [diff] [blame] | 940 | RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this)); |
| 941 | ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread, |
| 942 | this); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 943 | } |
Tomas Gunnarsson | 0fd4c4e | 2020-09-04 16:33:25 +0200 | [diff] [blame] | 944 | #endif |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 945 | |
Tomas Gunnarsson | 0fd4c4e | 2020-09-04 16:33:25 +0200 | [diff] [blame] | 946 | // Perhaps down the line we can get rid of this workaround and always require |
| 947 | // current_thread to be valid when Send() is called. |
| 948 | std::unique_ptr<rtc::Event> done_event; |
| 949 | if (!current_thread) |
| 950 | done_event.reset(new rtc::Event()); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 951 | |
Tomas Gunnarsson | 0fd4c4e | 2020-09-04 16:33:25 +0200 | [diff] [blame] | 952 | bool ready = false; |
Danil Chapovalov | 4bcf809 | 2022-07-06 19:42:34 +0200 | [diff] [blame] | 953 | absl::Cleanup cleanup = [this, &ready, current_thread, |
| 954 | done = done_event.get()] { |
| 955 | if (current_thread) { |
| 956 | CritScope cs(&crit_); |
| 957 | ready = true; |
| 958 | current_thread->socketserver()->WakeUp(); |
| 959 | } else { |
| 960 | done->Set(); |
| 961 | } |
| 962 | }; |
| 963 | PostTask([&msg, cleanup = std::move(cleanup)]() mutable { |
| 964 | msg.phandler->OnMessage(&msg); |
| 965 | }); |
Tomas Gunnarsson | 0fd4c4e | 2020-09-04 16:33:25 +0200 | [diff] [blame] | 966 | if (current_thread) { |
| 967 | bool waited = false; |
| 968 | crit_.Enter(); |
| 969 | while (!ready) { |
| 970 | crit_.Leave(); |
| 971 | current_thread->socketserver()->Wait(kForever, false); |
| 972 | waited = true; |
| 973 | crit_.Enter(); |
| 974 | } |
| 975 | crit_.Leave(); |
| 976 | |
| 977 | // Our Wait loop above may have consumed some WakeUp events for this |
| 978 | // Thread, that weren't relevant to this Send. Losing these WakeUps can |
| 979 | // cause problems for some SocketServers. |
| 980 | // |
| 981 | // Concrete example: |
| 982 | // Win32SocketServer on thread A calls Send on thread B. While processing |
| 983 | // the message, thread B Posts a message to A. We consume the wakeup for |
| 984 | // that Post while waiting for the Send to complete, which means that when |
| 985 | // we exit this loop, we need to issue another WakeUp, or else the Posted |
| 986 | // message won't be processed in a timely manner. |
| 987 | |
| 988 | if (waited) { |
| 989 | current_thread->socketserver()->WakeUp(); |
| 990 | } |
| 991 | } else { |
| 992 | done_event->Wait(rtc::Event::kForever); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 993 | } |
| 994 | } |
| 995 | |
Taylor Brandstetter | 5d97a9a | 2016-06-10 14:17:27 -0700 | [diff] [blame] | 996 | void Thread::InvokeInternal(const Location& posted_from, |
Danil Chapovalov | 8931345 | 2019-11-29 12:56:43 +0100 | [diff] [blame] | 997 | rtc::FunctionView<void()> functor) { |
Steve Anton | c5d7c52 | 2019-12-03 10:14:05 -0800 | [diff] [blame] | 998 | TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(), |
| 999 | "src_func", posted_from.function_name()); |
Danil Chapovalov | 8931345 | 2019-11-29 12:56:43 +0100 | [diff] [blame] | 1000 | |
| 1001 | class FunctorMessageHandler : public MessageHandler { |
| 1002 | public: |
| 1003 | explicit FunctorMessageHandler(rtc::FunctionView<void()> functor) |
Tomas Gunnarsson | 77baeee | 2020-09-24 22:39:21 +0200 | [diff] [blame] | 1004 | : functor_(functor) {} |
Danil Chapovalov | 8931345 | 2019-11-29 12:56:43 +0100 | [diff] [blame] | 1005 | void OnMessage(Message* msg) override { functor_(); } |
| 1006 | |
| 1007 | private: |
| 1008 | rtc::FunctionView<void()> functor_; |
| 1009 | } handler(functor); |
| 1010 | |
| 1011 | Send(posted_from, &handler); |
tommi@webrtc.org | 7c64ed2 | 2015-03-17 14:25:37 +0000 | [diff] [blame] | 1012 | } |
| 1013 | |
Tommi | 6866dc7 | 2020-05-15 10:11:56 +0200 | [diff] [blame] | 1014 | // Called by the ThreadManager when being set as the current thread. |
| 1015 | void Thread::EnsureIsCurrentTaskQueue() { |
| 1016 | task_queue_registration_ = |
| 1017 | std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this); |
| 1018 | } |
| 1019 | |
| 1020 | // Called by the ThreadManager when being set as the current thread. |
| 1021 | void Thread::ClearCurrentTaskQueue() { |
| 1022 | task_queue_registration_.reset(); |
| 1023 | } |
| 1024 | |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 1025 | void Thread::AllowInvokesToThread(Thread* thread) { |
Mirko Bonadei | 481e345 | 2021-07-30 13:57:25 +0200 | [diff] [blame] | 1026 | #if (!defined(NDEBUG) || RTC_DCHECK_IS_ON) |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 1027 | if (!IsCurrent()) { |
Danil Chapovalov | 5286dcf | 2022-07-18 17:04:56 +0200 | [diff] [blame] | 1028 | PostTask([thread, this]() { AllowInvokesToThread(thread); }); |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 1029 | return; |
| 1030 | } |
| 1031 | RTC_DCHECK_RUN_ON(this); |
| 1032 | allowed_threads_.push_back(thread); |
| 1033 | invoke_policy_enabled_ = true; |
| 1034 | #endif |
| 1035 | } |
| 1036 | |
| 1037 | void Thread::DisallowAllInvokes() { |
Mirko Bonadei | 481e345 | 2021-07-30 13:57:25 +0200 | [diff] [blame] | 1038 | #if (!defined(NDEBUG) || RTC_DCHECK_IS_ON) |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 1039 | if (!IsCurrent()) { |
Danil Chapovalov | 5286dcf | 2022-07-18 17:04:56 +0200 | [diff] [blame] | 1040 | PostTask([this]() { DisallowAllInvokes(); }); |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 1041 | return; |
| 1042 | } |
| 1043 | RTC_DCHECK_RUN_ON(this); |
| 1044 | allowed_threads_.clear(); |
| 1045 | invoke_policy_enabled_ = true; |
| 1046 | #endif |
| 1047 | } |
| 1048 | |
Tommi | fe04164 | 2021-04-07 10:08:28 +0200 | [diff] [blame] | 1049 | #if RTC_DCHECK_IS_ON |
| 1050 | uint32_t Thread::GetBlockingCallCount() const { |
| 1051 | RTC_DCHECK_RUN_ON(this); |
| 1052 | return blocking_call_count_; |
| 1053 | } |
| 1054 | uint32_t Thread::GetCouldBeBlockingCallCount() const { |
| 1055 | RTC_DCHECK_RUN_ON(this); |
| 1056 | return could_be_blocking_call_count_; |
| 1057 | } |
| 1058 | #endif |
| 1059 | |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 1060 | // Returns true if no policies added or if there is at least one policy |
Artem Titov | 96e3b99 | 2021-07-26 16:03:14 +0200 | [diff] [blame] | 1061 | // that permits invocation to `target` thread. |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 1062 | bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) { |
Mirko Bonadei | 481e345 | 2021-07-30 13:57:25 +0200 | [diff] [blame] | 1063 | #if (!defined(NDEBUG) || RTC_DCHECK_IS_ON) |
Artem Titov | dfc5f0d | 2020-07-03 12:09:26 +0200 | [diff] [blame] | 1064 | RTC_DCHECK_RUN_ON(this); |
| 1065 | if (!invoke_policy_enabled_) { |
| 1066 | return true; |
| 1067 | } |
| 1068 | for (const auto* thread : allowed_threads_) { |
| 1069 | if (thread == target) { |
| 1070 | return true; |
| 1071 | } |
| 1072 | } |
| 1073 | return false; |
| 1074 | #else |
| 1075 | return true; |
| 1076 | #endif |
| 1077 | } |
| 1078 | |
Danil Chapovalov | 912b3b8 | 2019-11-22 15:52:40 +0100 | [diff] [blame] | 1079 | void Thread::Delete() { |
| 1080 | Stop(); |
| 1081 | delete this; |
| 1082 | } |
| 1083 | |
Danil Chapovalov | 4bcf809 | 2022-07-06 19:42:34 +0200 | [diff] [blame] | 1084 | void Thread::PostTask(absl::AnyInvocable<void() &&> task) { |
| 1085 | // Though Post takes MessageData by raw pointer (last parameter), it still |
| 1086 | // takes it with ownership. |
| 1087 | Post(RTC_FROM_HERE, GetAnyInvocableMessageHandler(), |
| 1088 | /*id=*/0, new AnyInvocableMessage(std::move(task))); |
| 1089 | } |
| 1090 | |
| 1091 | void Thread::PostDelayedTask(absl::AnyInvocable<void() &&> task, |
| 1092 | webrtc::TimeDelta delay) { |
| 1093 | // This implementation does not support low precision yet. |
| 1094 | PostDelayedHighPrecisionTask(std::move(task), delay); |
| 1095 | } |
| 1096 | |
| 1097 | void Thread::PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task, |
| 1098 | webrtc::TimeDelta delay) { |
| 1099 | int delay_ms = delay.RoundUpTo(webrtc::TimeDelta::Millis(1)).ms<int>(); |
| 1100 | // Though PostDelayed takes MessageData by raw pointer (last parameter), |
| 1101 | // it still takes it with ownership. |
| 1102 | PostDelayed(RTC_FROM_HERE, delay_ms, GetAnyInvocableMessageHandler(), |
| 1103 | /*id=*/0, new AnyInvocableMessage(std::move(task))); |
| 1104 | } |
| 1105 | |
Niels Möller | 8909a63 | 2018-09-06 08:42:44 +0200 | [diff] [blame] | 1106 | bool Thread::IsProcessingMessagesForTesting() { |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 1107 | return (owned_ || IsCurrent()) && !IsQuitting(); |
Niels Möller | 8909a63 | 2018-09-06 08:42:44 +0200 | [diff] [blame] | 1108 | } |
| 1109 | |
Peter Boström | 0c4e06b | 2015-10-07 12:23:21 +0200 | [diff] [blame] | 1110 | void Thread::Clear(MessageHandler* phandler, |
| 1111 | uint32_t id, |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1112 | MessageList* removed) { |
| 1113 | CritScope cs(&crit_); |
Niels Möller | 5e007b7 | 2018-09-07 12:35:44 +0200 | [diff] [blame] | 1114 | ClearInternal(phandler, id, removed); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1115 | } |
| 1116 | |
| 1117 | bool Thread::ProcessMessages(int cmsLoop) { |
deadbeef | 22e0814 | 2017-06-12 14:30:28 -0700 | [diff] [blame] | 1118 | // Using ProcessMessages with a custom clock for testing and a time greater |
| 1119 | // than 0 doesn't work, since it's not guaranteed to advance the custom |
| 1120 | // clock's time, and may get stuck in an infinite loop. |
| 1121 | RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 || |
| 1122 | cmsLoop == kForever); |
Honghai Zhang | 82d7862 | 2016-05-06 11:29:15 -0700 | [diff] [blame] | 1123 | int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1124 | int cmsNext = cmsLoop; |
| 1125 | |
| 1126 | while (true) { |
Kári Tristan Helgason | 62b1345 | 2018-10-12 12:57:49 +0200 | [diff] [blame] | 1127 | #if defined(WEBRTC_MAC) |
| 1128 | ScopedAutoReleasePool pool; |
| 1129 | #endif |
kthelgason | de6adbe | 2017-02-22 00:42:11 -0800 | [diff] [blame] | 1130 | Message msg; |
| 1131 | if (!Get(&msg, cmsNext)) |
| 1132 | return !IsQuitting(); |
| 1133 | Dispatch(&msg); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1134 | |
kthelgason | de6adbe | 2017-02-22 00:42:11 -0800 | [diff] [blame] | 1135 | if (cmsLoop != kForever) { |
| 1136 | cmsNext = static_cast<int>(TimeUntil(msEnd)); |
| 1137 | if (cmsNext < 0) |
| 1138 | return true; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1139 | } |
| 1140 | } |
| 1141 | } |
| 1142 | |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 1143 | bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager, |
| 1144 | bool need_synchronize_access) { |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 1145 | RTC_DCHECK(!IsRunning()); |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 1146 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1147 | #if defined(WEBRTC_WIN) |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 1148 | if (need_synchronize_access) { |
| 1149 | // We explicitly ask for no rights other than synchronization. |
| 1150 | // This gives us the best chance of succeeding. |
| 1151 | thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId()); |
| 1152 | if (!thread_) { |
Mirko Bonadei | 675513b | 2017-11-09 11:09:25 +0100 | [diff] [blame] | 1153 | RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread."; |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 1154 | return false; |
| 1155 | } |
| 1156 | thread_id_ = GetCurrentThreadId(); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1157 | } |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1158 | #elif defined(WEBRTC_POSIX) |
| 1159 | thread_ = pthread_self(); |
| 1160 | #endif |
| 1161 | owned_ = false; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1162 | thread_manager->SetCurrentThread(this); |
| 1163 | return true; |
| 1164 | } |
| 1165 | |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 1166 | bool Thread::IsRunning() { |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 1167 | #if defined(WEBRTC_WIN) |
| 1168 | return thread_ != nullptr; |
| 1169 | #elif defined(WEBRTC_POSIX) |
| 1170 | return thread_ != 0; |
| 1171 | #endif |
| 1172 | } |
| 1173 | |
Taylor Brandstetter | 0867260 | 2018-03-02 15:20:33 -0800 | [diff] [blame] | 1174 | AutoThread::AutoThread() |
Mirko Bonadei | e5f4c6b | 2021-01-15 10:41:01 +0100 | [diff] [blame] | 1175 | : Thread(CreateDefaultSocketServer(), /*do_init=*/false) { |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1176 | if (!ThreadManager::Instance()->CurrentThread()) { |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 1177 | // DoInit registers with ThreadManager. Do that only if we intend to |
Niels Möller | 5a8f860 | 2019-06-12 11:30:59 +0200 | [diff] [blame] | 1178 | // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will |
| 1179 | // post a message to a queue that no running thread is serving. |
| 1180 | DoInit(); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1181 | ThreadManager::Instance()->SetCurrentThread(this); |
| 1182 | } |
| 1183 | } |
| 1184 | |
| 1185 | AutoThread::~AutoThread() { |
| 1186 | Stop(); |
Steve Anton | 3b80aac | 2017-10-19 10:17:12 -0700 | [diff] [blame] | 1187 | DoDestroy(); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1188 | if (ThreadManager::Instance()->CurrentThread() == this) { |
deadbeef | 37f5ecf | 2017-02-27 14:06:41 -0800 | [diff] [blame] | 1189 | ThreadManager::Instance()->SetCurrentThread(nullptr); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1190 | } |
| 1191 | } |
| 1192 | |
nisse | 7eaa4ea | 2017-05-08 05:25:41 -0700 | [diff] [blame] | 1193 | AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss) |
Taylor Brandstetter | 0867260 | 2018-03-02 15:20:33 -0800 | [diff] [blame] | 1194 | : Thread(ss, /*do_init=*/false) { |
| 1195 | DoInit(); |
nisse | 7eaa4ea | 2017-05-08 05:25:41 -0700 | [diff] [blame] | 1196 | old_thread_ = ThreadManager::Instance()->CurrentThread(); |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 1197 | // Temporarily set the current thread to nullptr so that we can keep checks |
| 1198 | // around that catch unintentional pointer overwrites. |
| 1199 | rtc::ThreadManager::Instance()->SetCurrentThread(nullptr); |
nisse | 7eaa4ea | 2017-05-08 05:25:41 -0700 | [diff] [blame] | 1200 | rtc::ThreadManager::Instance()->SetCurrentThread(this); |
| 1201 | if (old_thread_) { |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 1202 | ThreadManager::Remove(old_thread_); |
nisse | 7eaa4ea | 2017-05-08 05:25:41 -0700 | [diff] [blame] | 1203 | } |
| 1204 | } |
| 1205 | |
| 1206 | AutoSocketServerThread::~AutoSocketServerThread() { |
| 1207 | RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this); |
Steve Anton | 3b80aac | 2017-10-19 10:17:12 -0700 | [diff] [blame] | 1208 | // Stop and destroy the thread before clearing it as the current thread. |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 1209 | // Sometimes there are messages left in the Thread that will be |
Steve Anton | 3b80aac | 2017-10-19 10:17:12 -0700 | [diff] [blame] | 1210 | // destroyed by DoDestroy, and sometimes the destructors of the message and/or |
| 1211 | // its contents rely on this thread still being set as the current thread. |
| 1212 | Stop(); |
| 1213 | DoDestroy(); |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 1214 | rtc::ThreadManager::Instance()->SetCurrentThread(nullptr); |
nisse | 7eaa4ea | 2017-05-08 05:25:41 -0700 | [diff] [blame] | 1215 | rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_); |
| 1216 | if (old_thread_) { |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 1217 | ThreadManager::Add(old_thread_); |
nisse | 7eaa4ea | 2017-05-08 05:25:41 -0700 | [diff] [blame] | 1218 | } |
| 1219 | } |
| 1220 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1221 | } // namespace rtc |