xref: /openbmc/linux/tools/perf/util/sharded_mutex.c (revision e021ae7f)
1 // SPDX-License-Identifier: GPL-2.0
2 #include "sharded_mutex.h"
3 
4 #include <stdlib.h>
5 
6 struct sharded_mutex *sharded_mutex__new(size_t num_shards)
7 {
8 	struct sharded_mutex *result;
9 	size_t size;
10 	unsigned int bits;
11 
12 	for (bits = 0; ((size_t)1 << bits) < num_shards; bits++)
13 		;
14 
15 	size = sizeof(*result) + sizeof(struct mutex) * (1 << bits);
16 	result = malloc(size);
17 	if (!result)
18 		return NULL;
19 
20 	result->cap_bits = bits;
21 	for (size_t i = 0; i < ((size_t)1 << bits); i++)
22 		mutex_init(&result->mutexes[i]);
23 
24 	return result;
25 }
26 
27 void sharded_mutex__delete(struct sharded_mutex *sm)
28 {
29 	for (size_t i = 0; i < ((size_t)1 << sm->cap_bits); i++)
30 		mutex_destroy(&sm->mutexes[i]);
31 
32 	free(sm);
33 }
34