| 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 |
| 11 | #include "rtc_base/thread.h" |
| 12 |
| 13 | #include "absl/strings/string_view.h" |
| 14 | #include "api/task_queue/task_queue_base.h" |
| 15 | #include "api/units/time_delta.h" |
| 16 | #include "rtc_base/socket_server.h" |
| 17 |
| 18 | #if defined(WEBRTC_WIN) |
| 19 | #include <comdef.h> |
| 20 | #elif defined(WEBRTC_POSIX) |
| 21 | #include <time.h> |
| 22 | #else |
| 23 | #error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined." |
| 24 | #endif |
| 25 |
| 26 | #if defined(WEBRTC_WIN) |
| 27 | // Disable warning that we don't care about: |
| 28 | // warning C4722: destructor never returns, potential memory leak |
| 29 | #pragma warning(disable : 4722) |
| 30 | #endif |
| 31 |
| 32 | #include <stdio.h> |
| 33 |
| 34 | #include <utility> |
| 35 |
| 36 | #include "absl/algorithm/container.h" |
| 37 | #include "absl/cleanup/cleanup.h" |
| 38 | #include "api/sequence_checker.h" |
| 39 | #include "rtc_base/checks.h" |
| 40 | #include "rtc_base/event.h" |
| 41 | #include "rtc_base/internal/default_socket_server.h" |
| 42 | #include "rtc_base/logging.h" |
| 43 | #include "rtc_base/null_socket_server.h" |
| 44 | #include "rtc_base/synchronization/mutex.h" |
| 45 | #include "rtc_base/time_utils.h" |
| 46 | #include "rtc_base/trace_event.h" |
| 47 |
| 48 | #if defined(WEBRTC_MAC) |
| 49 | #include "rtc_base/system/cocoa_threading.h" |
| 50 |
| 51 | /* |
| 52 | * These are forward-declarations for methods that are part of the |
| 53 | * ObjC runtime. They are declared in the private header objc-internal.h. |
| 54 | * These calls are what clang inserts when using @autoreleasepool in ObjC, |
| 55 | * but here they are used directly in order to keep this file C++. |
| 56 | * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support |
| 57 | */ |
| 58 | extern "C" { |
| 59 | void* objc_autoreleasePoolPush(void); |
| 60 | void objc_autoreleasePoolPop(void* pool); |
| 61 | } |
| 62 |
| 63 | namespace { |
| 64 | class ScopedAutoReleasePool { |
| 65 | public: |
| 66 | ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {} |
| 67 | ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); } |
| 68 |
| 69 | private: |
| 70 | void* const pool_; |
| 71 | }; |
| 72 | } // namespace |
| 73 | #endif |
| 74 |
| 75 | namespace rtc { |
| 76 |
| 77 | using ::webrtc::MutexLock; |
| 78 | using ::webrtc::TimeDelta; |
| 79 |
| 80 | ThreadManager* ThreadManager::Instance() { |
| 81 | static ThreadManager* const thread_manager = new ThreadManager(); |
| 82 | return thread_manager; |
| 83 | } |
| 84 |
| 85 | ThreadManager::~ThreadManager() { |
| 86 | // By above RTC_DEFINE_STATIC_LOCAL. |
| 87 | RTC_DCHECK_NOTREACHED() << "ThreadManager should never be destructed."; |
| 88 | } |
| 89 |
| 90 | // static |
| 91 | void ThreadManager::Add(Thread* message_queue) { |
| 92 | return Instance()->AddInternal(message_queue); |
| 93 | } |
| 94 | void ThreadManager::AddInternal(Thread* message_queue) { |
| 95 | MutexLock cs(&crit_); |
| 96 | message_queues_.push_back(message_queue); |
| 97 | } |
| 98 |
| 99 | // static |
| 100 | void ThreadManager::Remove(Thread* message_queue) { |
| 101 | return Instance()->RemoveInternal(message_queue); |
| 102 | } |
| 103 | void ThreadManager::RemoveInternal(Thread* message_queue) { |
| 104 | { |
| 105 | MutexLock cs(&crit_); |
| 106 | std::vector<Thread*>::iterator iter; |
| 107 | iter = absl::c_find(message_queues_, message_queue); |
| 108 | if (iter != message_queues_.end()) { |
| 109 | message_queues_.erase(iter); |
| 110 | } |
| 111 | #if RTC_DCHECK_IS_ON |
| 112 | RemoveFromSendGraph(message_queue); |
| 113 | #endif |
| 114 | } |
| 115 | } |
| 116 |
| 117 | #if RTC_DCHECK_IS_ON |
| 118 | void ThreadManager::RemoveFromSendGraph(Thread* thread) { |
| 119 | for (auto it = send_graph_.begin(); it != send_graph_.end();) { |
| 120 | if (it->first == thread) { |
| 121 | it = send_graph_.erase(it); |
| 122 | } else { |
| 123 | it->second.erase(thread); |
| 124 | ++it; |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 |
| 129 | void ThreadManager::RegisterSendAndCheckForCycles(Thread* source, |
| 130 | Thread* target) { |
| 131 | RTC_DCHECK(source); |
| 132 | RTC_DCHECK(target); |
| 133 |
| 134 | MutexLock cs(&crit_); |
| 135 | std::deque<Thread*> all_targets({target}); |
| 136 | // We check the pre-existing who-sends-to-who graph for any path from target |
| 137 | // to source. This loop is guaranteed to terminate because per the send graph |
| 138 | // invariant, there are no cycles in the graph. |
| 139 | for (size_t i = 0; i < all_targets.size(); i++) { |
| 140 | const auto& targets = send_graph_[all_targets[i]]; |
| 141 | all_targets.insert(all_targets.end(), targets.begin(), targets.end()); |
| 142 | } |
| 143 | RTC_CHECK_EQ(absl::c_count(all_targets, source), 0) |
| 144 | << " send loop between " << source->name() << " and " << target->name(); |
| 145 |
| 146 | // We may now insert source -> target without creating a cycle, since there |
| 147 | // was no path from target to source per the prior CHECK. |
| 148 | send_graph_[source].insert(target); |
| 149 | } |
| 150 | #endif |
| 151 |
| 152 | // static |
| 153 | void ThreadManager::ProcessAllMessageQueuesForTesting() { |
| 154 | return Instance()->ProcessAllMessageQueuesInternal(); |
| 155 | } |
| 156 |
| 157 | void ThreadManager::ProcessAllMessageQueuesInternal() { |
| 158 | // This works by posting a delayed message at the current time and waiting |
| 159 | // for it to be dispatched on all queues, which will ensure that all messages |
| 160 | // that came before it were also dispatched. |
| 161 | std::atomic<int> queues_not_done(0); |
| 162 |
| 163 | { |
| 164 | MutexLock cs(&crit_); |
| 165 | for (Thread* queue : message_queues_) { |
| 166 | if (!queue->IsProcessingMessagesForTesting()) { |
| 167 | // If the queue is not processing messages, it can |
| 168 | // be ignored. If we tried to post a message to it, it would be dropped |
| 169 | // or ignored. |
| 170 | continue; |
| 171 | } |
| 172 | queues_not_done.fetch_add(1); |
| 173 | // Whether the task is processed, or the thread is simply cleared, |
| 174 | // queues_not_done gets decremented. |
| 175 | absl::Cleanup sub = [&queues_not_done] { queues_not_done.fetch_sub(1); }; |
| 176 | // Post delayed task instead of regular task to wait for all delayed tasks |
| 177 | // that are ready for processing. |
| 178 | queue->PostDelayedTask([sub = std::move(sub)] {}, TimeDelta::Zero()); |
| 179 | } |
| 180 | } |
| 181 |
| 182 | rtc::Thread* current = rtc::Thread::Current(); |
| 183 | // Note: One of the message queues may have been on this thread, which is |
| 184 | // why we can't synchronously wait for queues_not_done to go to 0; we need |
| 185 | // to process messages as well. |
| 186 | while (queues_not_done.load() > 0) { |
| 187 | if (current) { |
| 188 | current->ProcessMessages(0); |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 |
| 193 | // static |
| 194 | Thread* Thread::Current() { |
| 195 | ThreadManager* manager = ThreadManager::Instance(); |
| 196 | Thread* thread = manager->CurrentThread(); |
| 197 |
| 198 | return thread; |
| 199 | } |
| 200 |
| 201 | #if defined(WEBRTC_POSIX) |
| 202 | ThreadManager::ThreadManager() { |
| 203 | #if defined(WEBRTC_MAC) |
| 204 | InitCocoaMultiThreading(); |
| 205 | #endif |
| 206 | pthread_key_create(&key_, nullptr); |
| 207 | } |
| 208 |
| 209 | Thread* ThreadManager::CurrentThread() { |
| 210 | return static_cast<Thread*>(pthread_getspecific(key_)); |
| 211 | } |
| 212 |
| 213 | void ThreadManager::SetCurrentThreadInternal(Thread* thread) { |
| 214 | pthread_setspecific(key_, thread); |
| 215 | } |
| 216 | #endif |
| 217 |
| 218 | #if defined(WEBRTC_WIN) |
| 219 | ThreadManager::ThreadManager() : key_(TlsAlloc()) {} |
| 220 |
| 221 | Thread* ThreadManager::CurrentThread() { |
| 222 | return static_cast<Thread*>(TlsGetValue(key_)); |
| 223 | } |
| 224 |
| 225 | void ThreadManager::SetCurrentThreadInternal(Thread* thread) { |
| 226 | TlsSetValue(key_, thread); |
| 227 | } |
| 228 | #endif |
| 229 |
| 230 | void ThreadManager::SetCurrentThread(Thread* thread) { |
| 231 | #if RTC_DLOG_IS_ON |
| 232 | if (CurrentThread() && thread) { |
| 233 | RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?"; |
| 234 | } |
| 235 | #endif // RTC_DLOG_IS_ON |
| 236 |
| 237 | if (thread) { |
| 238 | thread->EnsureIsCurrentTaskQueue(); |
| 239 | } else { |
| 240 | Thread* current = CurrentThread(); |
| 241 | if (current) { |
| 242 | // The current thread is being cleared, e.g. as a result of |
| 243 | // UnwrapCurrent() being called or when a thread is being stopped |
| 244 | // (see PreRun()). This signals that the Thread instance is being detached |
| 245 | // from the thread, which also means that TaskQueue::Current() must not |
| 246 | // return a pointer to the Thread instance. |
| 247 | current->ClearCurrentTaskQueue(); |
| 248 | } |
| 249 | } |
| 250 |
| 251 | SetCurrentThreadInternal(thread); |
| 252 | } |
| 253 |
| 254 | void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) { |
| 255 | SetCurrentThreadInternal(thread); |
| 256 | } |
| 257 |
| 258 | Thread* ThreadManager::WrapCurrentThread() { |
| 259 | Thread* result = CurrentThread(); |
| 260 | if (nullptr == result) { |
| 261 | result = new Thread(CreateDefaultSocketServer()); |
| 262 | result->WrapCurrentWithThreadManager(this, true); |
| 263 | } |
| 264 | return result; |
| 265 | } |
| 266 |
| 267 | void ThreadManager::UnwrapCurrentThread() { |
| 268 | Thread* t = CurrentThread(); |
| 269 | if (t && !(t->IsOwned())) { |
| 270 | t->UnwrapCurrent(); |
| 271 | delete t; |
| 272 | } |
| 273 | } |
| 274 |
| 275 | Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls() |
| 276 | : thread_(Thread::Current()), |
| 277 | previous_state_(thread_->SetAllowBlockingCalls(false)) {} |
| 278 |
| 279 | Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() { |
| 280 | RTC_DCHECK(thread_->IsCurrent()); |
| 281 | thread_->SetAllowBlockingCalls(previous_state_); |
| 282 | } |
| 283 |
| 284 | #if RTC_DCHECK_IS_ON |
| 285 | Thread::ScopedCountBlockingCalls::ScopedCountBlockingCalls( |
| 286 | std::function<void(uint32_t, uint32_t)> callback) |
| 287 | : thread_(Thread::Current()), |
| 288 | base_blocking_call_count_(thread_->GetBlockingCallCount()), |
| 289 | base_could_be_blocking_call_count_( |
| 290 | thread_->GetCouldBeBlockingCallCount()), |
| 291 | result_callback_(std::move(callback)) {} |
| 292 |
| 293 | Thread::ScopedCountBlockingCalls::~ScopedCountBlockingCalls() { |
| 294 | if (GetTotalBlockedCallCount() >= min_blocking_calls_for_callback_) { |
| 295 | result_callback_(GetBlockingCallCount(), GetCouldBeBlockingCallCount()); |
| 296 | } |
| 297 | } |
| 298 |
| 299 | uint32_t Thread::ScopedCountBlockingCalls::GetBlockingCallCount() const { |
| 300 | return thread_->GetBlockingCallCount() - base_blocking_call_count_; |
| 301 | } |
| 302 |
| 303 | uint32_t Thread::ScopedCountBlockingCalls::GetCouldBeBlockingCallCount() const { |
| 304 | return thread_->GetCouldBeBlockingCallCount() - |
| 305 | base_could_be_blocking_call_count_; |
| 306 | } |
| 307 |
| 308 | uint32_t Thread::ScopedCountBlockingCalls::GetTotalBlockedCallCount() const { |
| 309 | return GetBlockingCallCount() + GetCouldBeBlockingCallCount(); |
| 310 | } |
| 311 | #endif |
| 312 |
| 313 | Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {} |
| 314 |
| 315 | Thread::Thread(std::unique_ptr<SocketServer> ss) |
| 316 | : Thread(std::move(ss), /*do_init=*/true) {} |
| 317 |
| 318 | Thread::Thread(SocketServer* ss, bool do_init) |
| 319 | : delayed_next_num_(0), |
| 320 | fInitialized_(false), |
| 321 | fDestroyed_(false), |
| 322 | stop_(0), |
| 323 | ss_(ss) { |
| 324 | RTC_DCHECK(ss); |
| 325 | ss_->SetMessageQueue(this); |
| 326 | SetName("Thread", this); // default name |
| 327 | if (do_init) { |
| 328 | DoInit(); |
| 329 | } |
| 330 | } |
| 331 |
| 332 | Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init) |
| 333 | : Thread(ss.get(), do_init) { |
| 334 | own_ss_ = std::move(ss); |
| 335 | } |
| 336 |
| 337 | Thread::~Thread() { |
| 338 | Stop(); |
| 339 | DoDestroy(); |
| 340 | } |
| 341 |
| 342 | void Thread::DoInit() { |
| 343 | if (fInitialized_) { |
| 344 | return; |
| 345 | } |
| 346 |
| 347 | fInitialized_ = true; |
| 348 | ThreadManager::Add(this); |
| 349 | } |
| 350 |
| 351 | void Thread::DoDestroy() { |
| 352 | if (fDestroyed_) { |
| 353 | return; |
| 354 | } |
| 355 |
| 356 | fDestroyed_ = true; |
| 357 | // The signal is done from here to ensure |
| 358 | // that it always gets called when the queue |
| 359 | // is going away. |
| 360 | if (ss_) { |
| 361 | ss_->SetMessageQueue(nullptr); |
| 362 | } |
| 363 | ThreadManager::Remove(this); |
| 364 | // Clear. |
| 365 | CurrentTaskQueueSetter set_current(this); |
| 366 | messages_ = {}; |
| 367 | delayed_messages_ = {}; |
| 368 | } |
| 369 |
| 370 | SocketServer* Thread::socketserver() { |
| 371 | return ss_; |
| 372 | } |
| 373 |
| 374 | void Thread::WakeUpSocketServer() { |
| 375 | ss_->WakeUp(); |
| 376 | } |
| 377 |
| 378 | void Thread::Quit() { |
| 379 | stop_.store(1, std::memory_order_release); |
| 380 | WakeUpSocketServer(); |
| 381 | } |
| 382 |
| 383 | bool Thread::IsQuitting() { |
| 384 | return stop_.load(std::memory_order_acquire) != 0; |
| 385 | } |
| 386 |
| 387 | void Thread::Restart() { |
| 388 | stop_.store(0, std::memory_order_release); |
| 389 | } |
| 390 |
| 391 | absl::AnyInvocable<void() &&> Thread::Get(int cmsWait) { |
| 392 | // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch |
| 393 |
| 394 | int64_t cmsTotal = cmsWait; |
| 395 | int64_t cmsElapsed = 0; |
| 396 | int64_t msStart = TimeMillis(); |
| 397 | int64_t msCurrent = msStart; |
| 398 | while (true) { |
| 399 | // Check for posted events |
| 400 | int64_t cmsDelayNext = kForever; |
| 401 | { |
| 402 | // All queue operations need to be locked, but nothing else in this loop |
| 403 | // can happen while holding the `mutex_`. |
| 404 | MutexLock lock(&mutex_); |
| 405 | // Check for delayed messages that have been triggered and calculate the |
| 406 | // next trigger time. |
| 407 | while (!delayed_messages_.empty()) { |
| 408 | if (msCurrent < delayed_messages_.top().run_time_ms) { |
| 409 | cmsDelayNext = |
| 410 | TimeDiff(delayed_messages_.top().run_time_ms, msCurrent); |
| 411 | break; |
| 412 | } |
| 413 | messages_.push(std::move(delayed_messages_.top().functor)); |
| 414 | delayed_messages_.pop(); |
| 415 | } |
| 416 | // Pull a message off the message queue, if available. |
| 417 | if (!messages_.empty()) { |
| 418 | absl::AnyInvocable<void()&&> task = std::move(messages_.front()); |
| 419 | messages_.pop(); |
| 420 | return task; |
| 421 | } |
| 422 | } |
| 423 |
| 424 | if (IsQuitting()) |
| 425 | break; |
| 426 |
| 427 | // Which is shorter, the delay wait or the asked wait? |
| 428 |
| 429 | int64_t cmsNext; |
| 430 | if (cmsWait == kForever) { |
| 431 | cmsNext = cmsDelayNext; |
| 432 | } else { |
| 433 | cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed); |
| 434 | if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext)) |
| 435 | cmsNext = cmsDelayNext; |
| 436 | } |
| 437 |
| 438 | { |
| 439 | // Wait and multiplex in the meantime |
| 440 | if (!ss_->Wait(cmsNext == kForever ? SocketServer::kForever |
| 441 | : webrtc::TimeDelta::Millis(cmsNext), |
| 442 | /*process_io=*/true)) |
| 443 | return nullptr; |
| 444 | } |
| 445 |
| 446 | // If the specified timeout expired, return |
| 447 |
| 448 | msCurrent = TimeMillis(); |
| 449 | cmsElapsed = TimeDiff(msCurrent, msStart); |
| 450 | if (cmsWait != kForever) { |
| 451 | if (cmsElapsed >= cmsWait) |
| 452 | return nullptr; |
| 453 | } |
| 454 | } |
| 455 | return nullptr; |
| 456 | } |
| 457 |
| 458 | void Thread::PostTaskImpl(absl::AnyInvocable<void() &&> task, |
| 459 | const PostTaskTraits& traits, |
| 460 | const webrtc::Location& location) { |
| 461 | if (IsQuitting()) { |
| 462 | return; |
| 463 | } |
| 464 |
| 465 | // Keep thread safe |
| 466 | // Add the message to the end of the queue |
| 467 | // Signal for the multiplexer to return |
| 468 |
| 469 | { |
| 470 | MutexLock lock(&mutex_); |
| 471 | messages_.push(std::move(task)); |
| 472 | } |
| 473 | WakeUpSocketServer(); |
| 474 | } |
| 475 |
| 476 | void Thread::PostDelayedTaskImpl(absl::AnyInvocable<void() &&> task, |
| 477 | webrtc::TimeDelta delay, |
| 478 | const PostDelayedTaskTraits& traits, |
| 479 | const webrtc::Location& location) { |
| 480 | if (IsQuitting()) { |
| 481 | return; |
| 482 | } |
| 483 |
| 484 | // Keep thread safe |
| 485 | // Add to the priority queue. Gets sorted soonest first. |
| 486 | // Signal for the multiplexer to return. |
| 487 |
| 488 | int64_t delay_ms = delay.RoundUpTo(webrtc::TimeDelta::Millis(1)).ms<int>(); |
| 489 | int64_t run_time_ms = TimeAfter(delay_ms); |
| 490 | { |
| 491 | MutexLock lock(&mutex_); |
| 492 | delayed_messages_.push({.delay_ms = delay_ms, |
| 493 | .run_time_ms = run_time_ms, |
| 494 | .message_number = delayed_next_num_, |
| 495 | .functor = std::move(task)}); |
| 496 | // If this message queue processes 1 message every millisecond for 50 days, |
| 497 | // we will wrap this number. Even then, only messages with identical times |
| 498 | // will be misordered, and then only briefly. This is probably ok. |
| 499 | ++delayed_next_num_; |
| 500 | RTC_DCHECK_NE(0, delayed_next_num_); |
| 501 | } |
| 502 | WakeUpSocketServer(); |
| 503 | } |
| 504 |
| 505 | int Thread::GetDelay() { |
| 506 | MutexLock lock(&mutex_); |
| 507 |
| 508 | if (!messages_.empty()) |
| 509 | return 0; |
| 510 |
| 511 | if (!delayed_messages_.empty()) { |
| 512 | int delay = TimeUntil(delayed_messages_.top().run_time_ms); |
| 513 | if (delay < 0) |
| 514 | delay = 0; |
| 515 | return delay; |
| 516 | } |
| 517 |
| 518 | return kForever; |
| 519 | } |
| 520 |
| 521 | void Thread::Dispatch(absl::AnyInvocable<void() &&> task) { |
| 522 | TRACE_EVENT0("webrtc", "Thread::Dispatch"); |
| 523 | RTC_DCHECK_RUN_ON(this); |
| 524 | int64_t start_time = TimeMillis(); |
| 525 | std::move(task)(); |
| 526 | int64_t end_time = TimeMillis(); |
| 527 | int64_t diff = TimeDiff(end_time, start_time); |
| 528 | if (diff >= dispatch_warning_ms_) { |
| 529 | RTC_LOG(LS_INFO) << "Message to " << name() << " took " << diff |
| 530 | << "ms to dispatch."; |
| 531 | // To avoid log spew, move the warning limit to only give warning |
| 532 | // for delays that are larger than the one observed. |
| 533 | dispatch_warning_ms_ = diff + 1; |
| 534 | } |
| 535 | } |
| 536 |
| 537 | bool Thread::IsCurrent() const { |
| 538 | return ThreadManager::Instance()->CurrentThread() == this; |
| 539 | } |
| 540 |
| 541 | std::unique_ptr<Thread> Thread::CreateWithSocketServer() { |
| 542 | return std::unique_ptr<Thread>(new Thread(CreateDefaultSocketServer())); |
| 543 | } |
| 544 |
| 545 | std::unique_ptr<Thread> Thread::Create() { |
| 546 | return std::unique_ptr<Thread>( |
| 547 | new Thread(std::unique_ptr<SocketServer>(new NullSocketServer()))); |
| 548 | } |
| 549 |
| 550 | bool Thread::SleepMs(int milliseconds) { |
| 551 | AssertBlockingIsAllowedOnCurrentThread(); |
| 552 |
| 553 | #if defined(WEBRTC_WIN) |
| 554 | ::Sleep(milliseconds); |
| 555 | return true; |
| 556 | #else |
| 557 | // POSIX has both a usleep() and a nanosleep(), but the former is deprecated, |
| 558 | // so we use nanosleep() even though it has greater precision than necessary. |
| 559 | struct timespec ts; |
| 560 | ts.tv_sec = milliseconds / 1000; |
| 561 | ts.tv_nsec = (milliseconds % 1000) * 1000000; |
| 562 | int ret = nanosleep(&ts, nullptr); |
| 563 | if (ret != 0) { |
| 564 | RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early"; |
| 565 | return false; |
| 566 | } |
| 567 | return true; |
| 568 | #endif |
| 569 | } |
| 570 |
| 571 | bool Thread::SetName(absl::string_view name, const void* obj) { |
| 572 | RTC_DCHECK(!IsRunning()); |
| 573 |
| 574 | name_ = std::string(name); |
| 575 | if (obj) { |
| 576 | // The %p specifier typically produce at most 16 hex digits, possibly with a |
| 577 | // 0x prefix. But format is implementation defined, so add some margin. |
| 578 | char buf[30]; |
| 579 | snprintf(buf, sizeof(buf), " 0x%p", obj); |
| 580 | name_ += buf; |
| 581 | } |
| 582 | return true; |
| 583 | } |
| 584 |
| 585 | void Thread::SetDispatchWarningMs(int deadline) { |
| 586 | if (!IsCurrent()) { |
| 587 | PostTask([this, deadline]() { SetDispatchWarningMs(deadline); }); |
| 588 | return; |
| 589 | } |
| 590 | RTC_DCHECK_RUN_ON(this); |
| 591 | dispatch_warning_ms_ = deadline; |
| 592 | } |
| 593 |
| 594 | bool Thread::Start() { |
| 595 | RTC_DCHECK(!IsRunning()); |
| 596 |
| 597 | if (IsRunning()) |
| 598 | return false; |
| 599 |
| 600 | Restart(); // reset IsQuitting() if the thread is being restarted |
| 601 |
| 602 | // Make sure that ThreadManager is created on the main thread before |
| 603 | // we start a new thread. |
| 604 | ThreadManager::Instance(); |
| 605 |
| 606 | owned_ = true; |
| 607 |
| 608 | #if defined(WEBRTC_WIN) |
| 609 | thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_); |
| 610 | if (!thread_) { |
| 611 | return false; |
| 612 | } |
| 613 | #elif defined(WEBRTC_POSIX) |
| 614 | pthread_attr_t attr; |
| 615 | pthread_attr_init(&attr); |
| 616 |
| 617 | int error_code = pthread_create(&thread_, &attr, PreRun, this); |
| 618 | if (0 != error_code) { |
| 619 | RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code; |
| 620 | thread_ = 0; |
| 621 | return false; |
| 622 | } |
| 623 | RTC_DCHECK(thread_); |
| 624 | #endif |
| 625 | return true; |
| 626 | } |
| 627 |
| 628 | bool Thread::WrapCurrent() { |
| 629 | return WrapCurrentWithThreadManager(ThreadManager::Instance(), true); |
| 630 | } |
| 631 |
| 632 | void Thread::UnwrapCurrent() { |
| 633 | // Clears the platform-specific thread-specific storage. |
| 634 | ThreadManager::Instance()->SetCurrentThread(nullptr); |
| 635 | #if defined(WEBRTC_WIN) |
| 636 | if (thread_ != nullptr) { |
| 637 | if (!CloseHandle(thread_)) { |
| 638 | RTC_LOG_GLE(LS_ERROR) |
| 639 | << "When unwrapping thread, failed to close handle."; |
| 640 | } |
| 641 | thread_ = nullptr; |
| 642 | thread_id_ = 0; |
| 643 | } |
| 644 | #elif defined(WEBRTC_POSIX) |
| 645 | thread_ = 0; |
| 646 | #endif |
| 647 | } |
| 648 |
| 649 | void Thread::SafeWrapCurrent() { |
| 650 | WrapCurrentWithThreadManager(ThreadManager::Instance(), false); |
| 651 | } |
| 652 |
| 653 | void Thread::Join() { |
| 654 | if (!IsRunning()) |
| 655 | return; |
| 656 |
| 657 | RTC_DCHECK(!IsCurrent()); |
| 658 | if (Current() && !Current()->blocking_calls_allowed_) { |
| 659 | RTC_LOG(LS_WARNING) << "Waiting for the thread to join, " |
| 660 | "but blocking calls have been disallowed"; |
| 661 | } |
| 662 |
| 663 | #if defined(WEBRTC_WIN) |
| 664 | RTC_DCHECK(thread_ != nullptr); |
| 665 | WaitForSingleObject(thread_, INFINITE); |
| 666 | CloseHandle(thread_); |
| 667 | thread_ = nullptr; |
| 668 | thread_id_ = 0; |
| 669 | #elif defined(WEBRTC_POSIX) |
| 670 | pthread_join(thread_, nullptr); |
| 671 | thread_ = 0; |
| 672 | #endif |
| 673 | } |
| 674 |
| 675 | bool Thread::SetAllowBlockingCalls(bool allow) { |
| 676 | RTC_DCHECK(IsCurrent()); |
| 677 | bool previous = blocking_calls_allowed_; |
| 678 | blocking_calls_allowed_ = allow; |
| 679 | return previous; |
| 680 | } |
| 681 |
| 682 | // static |
| 683 | void Thread::AssertBlockingIsAllowedOnCurrentThread() { |
| 684 | #if !defined(NDEBUG) |
| 685 | Thread* current = Thread::Current(); |
| 686 | RTC_DCHECK(!current || current->blocking_calls_allowed_); |
| 687 | #endif |
| 688 | } |
| 689 |
| 690 | // static |
| 691 | #if defined(WEBRTC_WIN) |
| 692 | DWORD WINAPI Thread::PreRun(LPVOID pv) { |
| 693 | #else |
| 694 | void* Thread::PreRun(void* pv) { |
| 695 | #endif |
| 696 | Thread* thread = static_cast<Thread*>(pv); |
| 697 | ThreadManager::Instance()->SetCurrentThread(thread); |
| 698 | rtc::SetCurrentThreadName(thread->name_.c_str()); |
| 699 | #if defined(WEBRTC_MAC) |
| 700 | ScopedAutoReleasePool pool; |
| 701 | #endif |
| 702 | thread->Run(); |
| 703 |
| 704 | ThreadManager::Instance()->SetCurrentThread(nullptr); |
| 705 | #ifdef WEBRTC_WIN |
| 706 | return 0; |
| 707 | #else |
| 708 | return nullptr; |
| 709 | #endif |
| 710 | } // namespace rtc |
| 711 |
| 712 | void Thread::Run() { |
| 713 | ProcessMessages(kForever); |
| 714 | } |
| 715 |
| 716 | bool Thread::IsOwned() { |
| 717 | RTC_DCHECK(IsRunning()); |
| 718 | return owned_; |
| 719 | } |
| 720 |
| 721 | void Thread::Stop() { |
| 722 | Thread::Quit(); |
| 723 | Join(); |
| 724 | } |
| 725 |
| 726 | void Thread::BlockingCallImpl(rtc::FunctionView<void()> functor, |
| 727 | const webrtc::Location& location) { |
| 728 | TRACE_EVENT0("webrtc", "Thread::BlockingCall"); |
| 729 |
| 730 | RTC_DCHECK(!IsQuitting()); |
| 731 | if (IsQuitting()) |
| 732 | return; |
| 733 |
| 734 | if (IsCurrent()) { |
| 735 | #if RTC_DCHECK_IS_ON |
| 736 | RTC_DCHECK(this->IsInvokeToThreadAllowed(this)); |
| 737 | RTC_DCHECK_RUN_ON(this); |
| 738 | could_be_blocking_call_count_++; |
| 739 | #endif |
| 740 | functor(); |
| 741 | return; |
| 742 | } |
| 743 |
| 744 | #if RTC_DCHECK_IS_ON |
| 745 | if (Thread* current_thread = Thread::Current()) { |
| 746 | RTC_DCHECK_RUN_ON(current_thread); |
| 747 | RTC_DCHECK(current_thread->blocking_calls_allowed_); |
| 748 | current_thread->blocking_call_count_++; |
| 749 | RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this)); |
| 750 | ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread, |
| 751 | this); |
| 752 | } |
| 753 | #endif |
| 754 |
| 755 | Event done; |
| 756 | absl::Cleanup cleanup = [&done] { done.Set(); }; |
| 757 | PostTask([functor, cleanup = std::move(cleanup)] { functor(); }); |
| 758 | done.Wait(Event::kForever); |
| 759 | } |
| 760 |
| 761 | // Called by the ThreadManager when being set as the current thread. |
| 762 | void Thread::EnsureIsCurrentTaskQueue() { |
| 763 | task_queue_registration_ = |
| 764 | std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this); |
| 765 | } |
| 766 |
| 767 | // Called by the ThreadManager when being set as the current thread. |
| 768 | void Thread::ClearCurrentTaskQueue() { |
| 769 | task_queue_registration_.reset(); |
| 770 | } |
| 771 |
| 772 | void Thread::AllowInvokesToThread(Thread* thread) { |
| 773 | #if (!defined(NDEBUG) || RTC_DCHECK_IS_ON) |
| 774 | if (!IsCurrent()) { |
| 775 | PostTask([thread, this]() { AllowInvokesToThread(thread); }); |
| 776 | return; |
| 777 | } |
| 778 | RTC_DCHECK_RUN_ON(this); |
| 779 | allowed_threads_.push_back(thread); |
| 780 | invoke_policy_enabled_ = true; |
| 781 | #endif |
| 782 | } |
| 783 |
| 784 | void Thread::DisallowAllInvokes() { |
| 785 | #if (!defined(NDEBUG) || RTC_DCHECK_IS_ON) |
| 786 | if (!IsCurrent()) { |
| 787 | PostTask([this]() { DisallowAllInvokes(); }); |
| 788 | return; |
| 789 | } |
| 790 | RTC_DCHECK_RUN_ON(this); |
| 791 | allowed_threads_.clear(); |
| 792 | invoke_policy_enabled_ = true; |
| 793 | #endif |
| 794 | } |
| 795 |
| 796 | #if RTC_DCHECK_IS_ON |
| 797 | uint32_t Thread::GetBlockingCallCount() const { |
| 798 | RTC_DCHECK_RUN_ON(this); |
| 799 | return blocking_call_count_; |
| 800 | } |
| 801 | uint32_t Thread::GetCouldBeBlockingCallCount() const { |
| 802 | RTC_DCHECK_RUN_ON(this); |
| 803 | return could_be_blocking_call_count_; |
| 804 | } |
| 805 | #endif |
| 806 |
| 807 | // Returns true if no policies added or if there is at least one policy |
| 808 | // that permits invocation to `target` thread. |
| 809 | bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) { |
| 810 | #if (!defined(NDEBUG) || RTC_DCHECK_IS_ON) |
| 811 | RTC_DCHECK_RUN_ON(this); |
| 812 | if (!invoke_policy_enabled_) { |
| 813 | return true; |
| 814 | } |
| 815 | for (const auto* thread : allowed_threads_) { |
| 816 | if (thread == target) { |
| 817 | return true; |
| 818 | } |
| 819 | } |
| 820 | return false; |
| 821 | #else |
| 822 | return true; |
| 823 | #endif |
| 824 | } |
| 825 |
| 826 | void Thread::Delete() { |
| 827 | Stop(); |
| 828 | delete this; |
| 829 | } |
| 830 |
| 831 | bool Thread::IsProcessingMessagesForTesting() { |
| 832 | return (owned_ || IsCurrent()) && !IsQuitting(); |
| 833 | } |
| 834 |
| 835 | bool Thread::ProcessMessages(int cmsLoop) { |
| 836 | // Using ProcessMessages with a custom clock for testing and a time greater |
| 837 | // than 0 doesn't work, since it's not guaranteed to advance the custom |
| 838 | // clock's time, and may get stuck in an infinite loop. |
| 839 | RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 || |
| 840 | cmsLoop == kForever); |
| 841 | int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop); |
| 842 | int cmsNext = cmsLoop; |
| 843 |
| 844 | while (true) { |
| 845 | #if defined(WEBRTC_MAC) |
| 846 | ScopedAutoReleasePool pool; |
| 847 | #endif |
| 848 | absl::AnyInvocable<void()&&> task = Get(cmsNext); |
| 849 | if (!task) |
| 850 | return !IsQuitting(); |
| 851 | Dispatch(std::move(task)); |
| 852 |
| 853 | if (cmsLoop != kForever) { |
| 854 | cmsNext = static_cast<int>(TimeUntil(msEnd)); |
| 855 | if (cmsNext < 0) |
| 856 | return true; |
| 857 | } |
| 858 | } |
| 859 | } |
| 860 |
| 861 | bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager, |
| 862 | bool need_synchronize_access) { |
| 863 | RTC_DCHECK(!IsRunning()); |
| 864 |
| 865 | #if defined(WEBRTC_WIN) |
| 866 | if (need_synchronize_access) { |
| 867 | // We explicitly ask for no rights other than synchronization. |
| 868 | // This gives us the best chance of succeeding. |
| 869 | thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId()); |
| 870 | if (!thread_) { |
| 871 | RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread."; |
| 872 | return false; |
| 873 | } |
| 874 | thread_id_ = GetCurrentThreadId(); |
| 875 | } |
| 876 | #elif defined(WEBRTC_POSIX) |
| 877 | thread_ = pthread_self(); |
| 878 | #endif |
| 879 | owned_ = false; |
| 880 | thread_manager->SetCurrentThread(this); |
| 881 | return true; |
| 882 | } |
| 883 |
| 884 | bool Thread::IsRunning() { |
| 885 | #if defined(WEBRTC_WIN) |
| 886 | return thread_ != nullptr; |
| 887 | #elif defined(WEBRTC_POSIX) |
| 888 | return thread_ != 0; |
| 889 | #endif |
| 890 | } |
| 891 |
| 892 | AutoThread::AutoThread() |
| 893 | : Thread(CreateDefaultSocketServer(), /*do_init=*/false) { |
| 894 | if (!ThreadManager::Instance()->CurrentThread()) { |
| 895 | // DoInit registers with ThreadManager. Do that only if we intend to |
| 896 | // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will |
| 897 | // post a message to a queue that no running thread is serving. |
| 898 | DoInit(); |
| 899 | ThreadManager::Instance()->SetCurrentThread(this); |
| 900 | } |
| 901 | } |
| 902 |
| 903 | AutoThread::~AutoThread() { |
| 904 | Stop(); |
| 905 | DoDestroy(); |
| 906 | if (ThreadManager::Instance()->CurrentThread() == this) { |
| 907 | ThreadManager::Instance()->SetCurrentThread(nullptr); |
| 908 | } |
| 909 | } |
| 910 |
| 911 | AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss) |
| 912 | : Thread(ss, /*do_init=*/false) { |
| 913 | DoInit(); |
| 914 | old_thread_ = ThreadManager::Instance()->CurrentThread(); |
| 915 | // Temporarily set the current thread to nullptr so that we can keep checks |
| 916 | // around that catch unintentional pointer overwrites. |
| 917 | rtc::ThreadManager::Instance()->SetCurrentThread(nullptr); |
| 918 | rtc::ThreadManager::Instance()->SetCurrentThread(this); |
| 919 | if (old_thread_) { |
| 920 | ThreadManager::Remove(old_thread_); |
| 921 | } |
| 922 | } |
| 923 |
| 924 | AutoSocketServerThread::~AutoSocketServerThread() { |
| 925 | RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this); |
| 926 | // Stop and destroy the thread before clearing it as the current thread. |
| 927 | // Sometimes there are messages left in the Thread that will be |
| 928 | // destroyed by DoDestroy, and sometimes the destructors of the message and/or |
| 929 | // its contents rely on this thread still being set as the current thread. |
| 930 | Stop(); |
| 931 | DoDestroy(); |
| 932 | rtc::ThreadManager::Instance()->SetCurrentThread(nullptr); |
| 933 | rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_); |
| 934 | if (old_thread_) { |
| 935 | ThreadManager::Add(old_thread_); |
| 936 | } |
| 937 | } |
| 938 |
| 939 | } // namespace rtc |
| 940 |