begin/endTemporaryMemory thread safe?

Each of the multithreaded tasks gets it's memory using BeginTemporaryMemory in BeginTaskWithMemory, and releases it with EndTemporaryMemory in EndTaskWithMemory.

BeginTemporaryMemory returns a temporary_memory structure which contains the arena and the amount of it used at the time it is called. When EndTemporaryMemory is called passing that temporary_memory structure back, the arena's Used structure member is reset to what is was before, effectively freeing the temporary memory.

But what happens when one task gets temporary memory, say temp1, with temp1.Used == 2000, then another task gets temp2 with temp2.Used == 2200 and temp1 is freed before temp2.

arena->Used will be set to 2000, then when temp2 tries to free it's memory, it will try to set arena->Used to 2200, effectively a memory allocation.

When this happens the assert in EndTemporaryMemory (Arena->Used >= TempMem.Used) will fire.

Am I understanding this properly?
That should not be a problem because the memory is coming from the thread's arena, which is unique to that thread.

- Casey
I think that's true for the renderer. But it is not clear to me if each thread of the threaded sound loading gets it's own arena.

In GameGetSoundSamples the transtate is set with "transient_state *TranState = (transient_state *)Memory->TransientStorage;", then "LoadSound(TranState->Assets, PlayingSound->ID);" is called using the same global arena for every sound load.

I'm not sure if I understand this, sorry if it sounds dumb.
I just realized that in BeginTaskWithMemory, that each task is allocated a separate "task_with_memory" from the global arena.

The problem is, I am hitting this assert, "(Arena->Used >= TempMem.Used)" in EndTemporaryMemory when a sound's temporary memory is being released and I can't find out why.
If I remove this assert the game runs normally.
I think I've found the problem.

In GameGetSoundSamples when the channels are allocated, "real32 *RealChannel0/1 = PushArray(&TranState->TranArena, SoundBuffer->SampleCount, real32);", the "TranState->TranArena.Used" is incremented by the "SoundBuffer->SampleCount".

The sound code on the platform I'm running on, hhxcb, has buffer underruns, which sets "SoundBuffer->SampleCount" negative.

I was wondering when those underruns were going to cause a problem :)

Well, at least I learnt more about how the memory management works.
That would definitely do it, yes :P

- Casey