Check if the thread should terminate before write.
Use a semaphore for buffer management.

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