dblockpool_alloc.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include <stdlib.h>
  2. #include "private.h"
  3. /*--------------------------------------------------------- */
  4. void *lub_dblockpool_alloc(lub_dblockpool_t * this)
  5. {
  6. void *result = NULL;
  7. lub_dblockpool_chunk_t *chunk;
  8. unsigned chunk_count = 0;
  9. /* first find a chunk which can service this request */
  10. for (chunk = this->first_chunk; chunk; chunk = chunk->next) {
  11. chunk_count++;
  12. /* try and get a block from this chunk */
  13. result = lub_blockpool_alloc(&chunk->pool);
  14. if (NULL != result) {
  15. /* got some memory */
  16. break;
  17. }
  18. }
  19. if ((NULL == result)
  20. && (!this->max_chunks || (chunk_count < this->max_chunks))) {
  21. /* dynamically allocate a new chunk */
  22. chunk =
  23. malloc(sizeof(lub_dblockpool_chunk_t) +
  24. (this->block_size * this->chunk_size));
  25. if (NULL != chunk) {
  26. /* configure the new chunk */
  27. chunk->next = this->first_chunk;
  28. lub_blockpool_init(&chunk->pool,
  29. &chunk[1],
  30. this->block_size, this->chunk_size);
  31. this->first_chunk = chunk;
  32. chunk->count = 0;
  33. /* now allocate the memory */
  34. result = lub_blockpool_alloc(&chunk->pool);
  35. }
  36. }
  37. if ((NULL != result) && (NULL != chunk)) {
  38. /* track the number of allocations */
  39. chunk->count++;
  40. }
  41. return result;
  42. }
  43. /*--------------------------------------------------------- */