Having static variable `cpus` in libbpf_num_possible_cpus function without guarding it with mutex makes this function thread-unsafe.
If multiple threads accessing this function, in the current form; it leads to incrementing the static variable value `cpus` in the multiple of total available CPUs. Let caching the number of possile CPUs handled by libbpf's users than this library itself; and let this function be rock bottom one which reads and parse the file (/sys/devices/system/cpu/possible) everytime it gets called to simplify the things. Fixes: 6446b3155521 (bpf: add a new API libbpf_num_possible_cpus()) Signed-off-by: Takshak Chahande <ctaks...@fb.com> Acked-by: Andrey Ignatov <r...@fb.com> --- tools/lib/bpf/libbpf.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c index ead915aec349..e7ac0e02287e 100644 --- a/tools/lib/bpf/libbpf.c +++ b/tools/lib/bpf/libbpf.c @@ -4998,14 +4998,11 @@ int libbpf_num_possible_cpus(void) static const char *fcpu = "/sys/devices/system/cpu/possible"; int len = 0, n = 0, il = 0, ir = 0; unsigned int start = 0, end = 0; - static int cpus; char buf[128]; int error = 0; + int cpus = 0; int fd = -1; - if (cpus > 0) - return cpus; - fd = open(fcpu, O_RDONLY); if (fd < 0) { error = errno; -- 2.17.1