Use a semaphore for buffer management.

Replace mutex with semaphore in the manage and write threads. Stop
writing samples when all buffers are filled.