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 #include "src/core/lib/gprpp/crash.h"
34
35 static long ncpus = 0;
36
37 static pthread_key_t thread_id_key;
38
init_ncpus()39 static void init_ncpus() {
40 ncpus = sysconf(_SC_NPROCESSORS_CONF);
41 if (ncpus < 1 || ncpus > INT32_MAX) {
42 gpr_log(GPR_ERROR, "Cannot determine number of CPUs: assuming 1");
43 ncpus = 1;
44 }
45 }
46
gpr_cpu_num_cores(void)47 unsigned gpr_cpu_num_cores(void) {
48 static gpr_once once = GPR_ONCE_INIT;
49 gpr_once_init(&once, init_ncpus);
50 return (unsigned)ncpus;
51 }
52
delete_thread_id(void * value)53 static void delete_thread_id(void* value) {
54 if (value) {
55 free(value);
56 }
57 }
58
init_thread_id_key(void)59 static void init_thread_id_key(void) {
60 pthread_key_create(&thread_id_key, delete_thread_id);
61 }
62
gpr_cpu_current_cpu(void)63 unsigned gpr_cpu_current_cpu(void) {
64 // NOTE: there's no way I know to return the actual cpu index portably...
65 // most code that's using this is using it to shard across work queues though,
66 // so here we use thread identity instead to achieve a similar though not
67 // identical effect
68 static gpr_once once = GPR_ONCE_INIT;
69 gpr_once_init(&once, init_thread_id_key);
70
71 unsigned int* thread_id =
72 static_cast<unsigned int*>(pthread_getspecific(thread_id_key));
73 if (thread_id == nullptr) {
74 // Note we cannot use gpr_malloc here because this allocation can happen in
75 // a main thread and will only be free'd when the main thread exits, which
76 // will cause our internal memory counters to believe it is a leak.
77 thread_id = static_cast<unsigned int*>(malloc(sizeof(unsigned int)));
78 pthread_setspecific(thread_id_key, thread_id);
79 }
80
81 return (unsigned)grpc_core::HashPointer(thread_id, gpr_cpu_num_cores());
82 }
83
84 #endif // GPR_CPU_POSIX
85