blob: a404849c72b4cefd56f1f5457092cff0a23d7aa8 [file] [log] [blame]
kthelgason61abe152017-03-29 02:32:36 -07001/*
2 * Copyright 2017 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 Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/thread.h"
kthelgason61abe152017-03-29 02:32:36 -070012
13#import <Foundation/Foundation.h>
14
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020015#include "rtc_base/platform_thread.h"
kthelgason61abe152017-03-29 02:32:36 -070016
17/*
18 * This file contains platform-specific implementations for several
19 * methods in rtc::Thread.
20 */
21
22namespace {
23void InitCocoaMultiThreading() {
24 if ([NSThread isMultiThreaded] == NO) {
25 // The sole purpose of this autorelease pool is to avoid a console
26 // message on Leopard that tells us we're autoreleasing the thread
27 // with no autorelease pool in place.
28 @autoreleasepool {
29 [NSThread detachNewThreadSelector:@selector(class)
30 toTarget:[NSObject class]
31 withObject:nil];
32 }
33 }
34
35 RTC_DCHECK([NSThread isMultiThreaded]);
36}
37}
38
39namespace rtc {
40
Tommi51492422017-12-04 15:18:23 +010041ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
kthelgason61abe152017-03-29 02:32:36 -070042 pthread_key_create(&key_, nullptr);
kthelgason61abe152017-03-29 02:32:36 -070043 // This is necessary to alert the cocoa runtime of the fact that
44 // we are running in a multithreaded environment.
45 InitCocoaMultiThreading();
46}
47
kthelgason61abe152017-03-29 02:32:36 -070048// static
49void* Thread::PreRun(void* pv) {
50 ThreadInit* init = static_cast<ThreadInit*>(pv);
51 ThreadManager::Instance()->SetCurrentThread(init->thread);
52 rtc::SetCurrentThreadName(init->thread->name_.c_str());
53 @autoreleasepool {
54 if (init->runnable) {
55 init->runnable->Run(init->thread);
56 } else {
57 init->thread->Run();
58 }
59 }
Tommi51492422017-12-04 15:18:23 +010060 ThreadManager::Instance()->SetCurrentThread(nullptr);
kthelgason61abe152017-03-29 02:32:36 -070061 delete init;
62 return nullptr;
63}
64
65bool Thread::ProcessMessages(int cmsLoop) {
66 int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
67 int cmsNext = cmsLoop;
68
69 while (true) {
70 @autoreleasepool {
71 Message msg;
72 if (!Get(&msg, cmsNext))
73 return !IsQuitting();
74 Dispatch(&msg);
75
76 if (cmsLoop != kForever) {
77 cmsNext = static_cast<int>(TimeUntil(msEnd));
78 if (cmsNext < 0)
79 return true;
80 }
81 }
82 }
83}
84} // namespace rtc