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 <grpc/support/cpu.h>
25 #include <grpc/support/sync.h>
26 #include <pthread.h>
27 #include <string.h>
28 #include <unistd.h>
29
30 #include "absl/log/log.h"
31 #include "src/core/util/crash.h"
32 #include "src/core/util/useful.h"
33
34 static long ncpus = 0;
35
36 static pthread_key_t thread_id_key;
37
init_ncpus()38 static void init_ncpus() {
39 ncpus = sysconf(_SC_NPROCESSORS_CONF);
40 if (ncpus < 1 || ncpus > INT32_MAX) {
41 LOG(ERROR) << "Cannot determine number of CPUs: assuming 1";
42 ncpus = 1;
43 }
44 }
45
gpr_cpu_num_cores(void)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
delete_thread_id(void * value)52 static void delete_thread_id(void* value) {
53 if (value) {
54 free(value);
55 }
56 }
57
init_thread_id_key(void)58 static void init_thread_id_key(void) {
59 pthread_key_create(&thread_id_key, delete_thread_id);
60 }
61
gpr_cpu_current_cpu(void)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)grpc_core::HashPointer(thread_id, gpr_cpu_num_cores());
81 }
82
83 #endif // GPR_CPU_POSIX
84