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