blob: ab42d6e4e16505f604a638c462f910c4b3cf1052 [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
41ThreadManager::ThreadManager() {
nisse7866cfe2017-04-26 01:45:31 -070042 main_thread_ref_ = CurrentThreadRef();
kthelgason61abe152017-03-29 02:32:36 -070043 pthread_key_create(&key_, nullptr);
kthelgason61abe152017-03-29 02:32:36 -070044 // This is necessary to alert the cocoa runtime of the fact that
45 // we are running in a multithreaded environment.
46 InitCocoaMultiThreading();
47}
48
kthelgason61abe152017-03-29 02:32:36 -070049// static
50void* Thread::PreRun(void* pv) {
51 ThreadInit* init = static_cast<ThreadInit*>(pv);
52 ThreadManager::Instance()->SetCurrentThread(init->thread);
53 rtc::SetCurrentThreadName(init->thread->name_.c_str());
54 @autoreleasepool {
55 if (init->runnable) {
56 init->runnable->Run(init->thread);
57 } else {
58 init->thread->Run();
59 }
60 }
61 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