CNDP 22.08.0
Loading...
Searching...
No Matches
cthread_objcache.h
1/* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright (c) 2019-2022 Intel Corporation
3 */
4
5#ifndef _CTHREAD_OBJCACHE_H_
6#define _CTHREAD_OBJCACHE_H_
7
8#include <string.h>
9
10#include <cne_per_thread.h>
11
12#include "cthread_int.h"
13#include "cthread_queue.h"
14
15#ifdef __cplusplus
16extern "C" {
17#endif
18
19CNE_DECLARE_PER_THREAD(struct cthread_sched *, this_sched);
20
21struct cthread_objcache {
22 struct cthread_queue *q;
23 size_t obj_size;
24 int prealloc_size;
25 char name[CTHREAD_NAME_SIZE];
26};
27
40static inline struct cthread_objcache *
41_cthread_objcache_create(const char *name, size_t obj_size, int prealloc_size)
42{
43 struct cthread_objcache *c = calloc(1, sizeof(struct cthread_objcache));
44
45 if (c == NULL)
46 return NULL;
47
48 c->q = _cthread_queue_create("cache queue");
49 if (c->q == NULL) {
50 free(c);
51 return NULL;
52 }
53 c->obj_size = obj_size;
54 c->prealloc_size = prealloc_size;
55
56 c->name[0] = '\0';
57 if (name != NULL)
58 strlcpy(c->name, name, sizeof(c->name));
59
60 return c;
61}
62
71static inline int
72_cthread_objcache_destroy(struct cthread_objcache *c)
73{
74 if (c == NULL)
75 return 0;
76 if (_cthread_queue_destroy(c->q) == 0) {
77 free(c);
78 return 0;
79 }
80 return -1;
81}
82
91static inline void *
92_cthread_objcache_alloc(struct cthread_objcache *c)
93{
94 int i;
95 void *data;
96 struct cthread_queue *q = c->q;
97 size_t obj_size = c->obj_size;
98 int prealloc_size = c->prealloc_size;
99
100 data = _cthread_queue_remove(q);
101
102 if (data == NULL) {
103 for (i = 0; i < prealloc_size; i++) {
104 data = calloc(1, obj_size);
105 if (data == NULL)
106 return NULL;
107
108 _cthread_queue_insert_mp(q, data);
109 }
110 data = _cthread_queue_remove(q);
111 }
112 return data;
113}
114
121static inline void
122_cthread_objcache_free(struct cthread_objcache *c, void *obj)
123{
124 _cthread_queue_insert_mp(c->q, obj);
125}
126
127#ifdef __cplusplus
128}
129#endif
130
131#endif /* _CTHREAD_OBJCACHE_H_ */
#define CNE_DECLARE_PER_THREAD(type, name)