Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc-cloned / deps / grpc / src / core / lib / gpr / cpu_posix.cc
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 #include <grpc/support/port_platform.h>
20
21 #if defined(GPR_CPU_POSIX)
22
23 #include <errno.h>
24 #include <pthread.h>
25 #include <string.h>
26 #include <unistd.h>
27
28 #include <grpc/support/cpu.h>
29 #include <grpc/support/log.h>
30 #include <grpc/support/sync.h>
31
32 #include "src/core/lib/gpr/useful.h"
33
34 static long ncpus = 0;
35
36 static pthread_key_t thread_id_key;
37
38 static void init_ncpus() {
39   ncpus = sysconf(_SC_NPROCESSORS_CONF);
40   if (ncpus < 1 || ncpus > INT32_MAX) {
41     gpr_log(GPR_ERROR, "Cannot determine number of CPUs: assuming 1");
42     ncpus = 1;
43   }
44 }
45
46 unsigned gpr_cpu_num_cores(void) {
47   static gpr_once once = GPR_ONCE_INIT;
48   gpr_once_init(&once, init_ncpus);
49   return (unsigned)ncpus;
50 }
51
52 static void delete_thread_id(void* value) {
53   if (value) {
54     free(value);
55   }
56 }
57
58 static void init_thread_id_key(void) {
59   pthread_key_create(&thread_id_key, delete_thread_id);
60 }
61
62 unsigned gpr_cpu_current_cpu(void) {
63   /* NOTE: there's no way I know to return the actual cpu index portably...
64      most code that's using this is using it to shard across work queues though,
65      so here we use thread identity instead to achieve a similar though not
66      identical effect */
67   static gpr_once once = GPR_ONCE_INIT;
68   gpr_once_init(&once, init_thread_id_key);
69
70   unsigned int* thread_id =
71       static_cast<unsigned int*>(pthread_getspecific(thread_id_key));
72   if (thread_id == nullptr) {
73     // Note we cannot use gpr_malloc here because this allocation can happen in
74     // a main thread and will only be free'd when the main thread exits, which
75     // will cause our internal memory counters to believe it is a leak.
76     thread_id = static_cast<unsigned int*>(malloc(sizeof(unsigned int)));
77     pthread_setspecific(thread_id_key, thread_id);
78   }
79
80   return (unsigned)GPR_HASH_POINTER(thread_id, gpr_cpu_num_cores());
81 }
82
83 #endif /* GPR_CPU_POSIX */