mutex_allocator.odin 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #+build !freestanding
  2. package mem
  3. import "core:sync"
  4. /*
  5. The data for mutex allocator.
  6. */
  7. Mutex_Allocator :: struct {
  8. backing: Allocator,
  9. mutex: sync.Mutex,
  10. }
  11. /*
  12. Initialize the mutex allocator.
  13. This procedure initializes the mutex allocator using `backin_allocator` as the
  14. allocator that will be used to pass all allocation requests through.
  15. */
  16. mutex_allocator_init :: proc(m: ^Mutex_Allocator, backing_allocator: Allocator) {
  17. m.backing = backing_allocator
  18. m.mutex = {}
  19. }
  20. /*
  21. Mutex allocator.
  22. The mutex allocator is a wrapper for allocators that is used to serialize all
  23. allocator requests across multiple threads.
  24. */
  25. @(require_results)
  26. mutex_allocator :: proc(m: ^Mutex_Allocator) -> Allocator {
  27. return Allocator{
  28. procedure = mutex_allocator_proc,
  29. data = m,
  30. }
  31. }
  32. mutex_allocator_proc :: proc(
  33. allocator_data: rawptr,
  34. mode: Allocator_Mode,
  35. size: int,
  36. alignment: int,
  37. old_memory: rawptr,
  38. old_size: int,
  39. loc := #caller_location,
  40. ) -> (result: []byte, err: Allocator_Error) {
  41. m := (^Mutex_Allocator)(allocator_data)
  42. sync.mutex_guard(&m.mutex)
  43. return m.backing.procedure(m.backing.data, mode, size, alignment, old_memory, old_size, loc)
  44. }