ucx/mempool.c

changeset 141
c466e2a6cbd0
parent 138
7800811078b8
child 158
81d580042da1
equal deleted inserted replaced
140:15f871f50bfd 141:c466e2a6cbd0
88 return EXIT_FAILURE; 88 return EXIT_FAILURE;
89 } 89 }
90 } 90 }
91 91
92 void *ucx_mempool_malloc(UcxMempool *pool, size_t n) { 92 void *ucx_mempool_malloc(UcxMempool *pool, size_t n) {
93 if (pool->ndata >= pool->size) {
94 // The hard coded 16 is documented for this function and ucx_mempool_new
95 if (ucx_mempool_chcap(pool, pool->size + 16) == EXIT_FAILURE) {
96 return NULL;
97 }
98 }
99
93 ucx_memchunk *mem = (ucx_memchunk*)malloc(sizeof(ucx_destructor) + n); 100 ucx_memchunk *mem = (ucx_memchunk*)malloc(sizeof(ucx_destructor) + n);
94 if (!mem) { 101 if (!mem) {
95 return NULL; 102 return NULL;
96 } 103 }
97
98 if (pool->ndata >= pool->size) {
99 // The hard coded 16 is documented for this function and ucx_mempool_new
100 ucx_mempool_chcap(pool, pool->size + 16);
101 }
102 104
103 mem->destructor = NULL; 105 mem->destructor = NULL;
104 pool->data[pool->ndata] = mem; 106 pool->data[pool->ndata] = mem;
105 pool->ndata++; 107 pool->ndata++;
106 108
129 return newm + sizeof(ucx_destructor); 131 return newm + sizeof(ucx_destructor);
130 } 132 }
131 } 133 }
132 fprintf(stderr, "FATAL: 0x%08" PRIxPTR" not in mpool 0x%08" PRIxPTR"\n", 134 fprintf(stderr, "FATAL: 0x%08" PRIxPTR" not in mpool 0x%08" PRIxPTR"\n",
133 (intptr_t)ptr, (intptr_t)pool); 135 (intptr_t)ptr, (intptr_t)pool);
134 exit(1); 136 exit(EXIT_FAILURE);
135 } else { 137 } else {
136 return newm + sizeof(ucx_destructor); 138 return newm + sizeof(ucx_destructor);
137 } 139 }
138 } 140 }
139 141
140 void ucx_mempool_free(UcxMempool *pool, void *ptr) { 142 void ucx_mempool_free(UcxMempool *pool, void *ptr) {
141 ucx_memchunk *chunk = (ucx_memchunk*)((char*)ptr-sizeof(ucx_destructor)); 143 ucx_memchunk *chunk = (ucx_memchunk*)((char*)ptr-sizeof(ucx_destructor));
142 for(size_t i=0 ; i<pool->ndata ; i++) { 144 for(size_t i=0 ; i<pool->ndata ; i++) {
143 if(chunk == pool->data[i]) { 145 if(chunk == pool->data[i]) {
144 if(chunk->destructor != NULL) { 146 if(chunk->destructor != NULL) {
145 chunk->destructor(&chunk->c); 147 chunk->destructor(&(chunk->c));
146 } 148 }
147 free(chunk); 149 free(chunk);
148 size_t last_index = pool->ndata - 1; 150 size_t last_index = pool->ndata - 1;
149 if(i != last_index) { 151 if(i != last_index) {
150 pool->data[i] = pool->data[last_index]; 152 pool->data[i] = pool->data[last_index];
153 pool->data[last_index] = NULL;
151 } 154 }
152 pool->ndata--; 155 pool->ndata--;
153 return; 156 return;
154 } 157 }
155 } 158 }

mercurial