platform_thread_mac.mm revision 3f50c38dc070f4bb515c1b64450dae14f316474e
1// Copyright (c) 2010 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/threading/platform_thread.h"
6
7#import <Foundation/Foundation.h>
8#include <dlfcn.h>
9
10#include "base/logging.h"
11
12namespace base {
13
14// If Cocoa is to be used on more than one thread, it must know that the
15// application is multithreaded.  Since it's possible to enter Cocoa code
16// from threads created by pthread_thread_create, Cocoa won't necessarily
17// be aware that the application is multithreaded.  Spawning an NSThread is
18// enough to get Cocoa to set up for multithreaded operation, so this is done
19// if necessary before pthread_thread_create spawns any threads.
20//
21// http://developer.apple.com/documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/chapter_4_section_4.html
22void InitThreading() {
23  static BOOL multithreaded = [NSThread isMultiThreaded];
24  if (!multithreaded) {
25    // +[NSObject class] is idempotent.
26    [NSThread detachNewThreadSelector:@selector(class)
27                             toTarget:[NSObject class]
28                           withObject:nil];
29    multithreaded = YES;
30
31    DCHECK([NSThread isMultiThreaded]);
32  }
33}
34
35// static
36void PlatformThread::SetName(const char* name) {
37  // pthread_setname_np is only available in 10.6 or later, so test
38  // for it at runtime.
39  int (*dynamic_pthread_setname_np)(const char*);
40  *reinterpret_cast<void**>(&dynamic_pthread_setname_np) =
41      dlsym(RTLD_DEFAULT, "pthread_setname_np");
42  if (!dynamic_pthread_setname_np)
43    return;
44
45  // Mac OS X does not expose the length limit of the name, so
46  // hardcode it.
47  const int kMaxNameLength = 63;
48  std::string shortened_name = std::string(name).substr(0, kMaxNameLength);
49  // pthread_setname() fails (harmlessly) in the sandbox, ignore when it does.
50  // See http://crbug.com/47058
51  dynamic_pthread_setname_np(shortened_name.c_str());
52}
53
54}  // namespace base
55