Does this critical section have to be this big? Can you move the allocation and the loop out of it somehow?