dblockpool_alloc.c 1.6 KB

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