Threading question from a newbie

I’m writing an object that is able to write audio stream to disk.

I have a Writer class that stores data in a long buffer. I saw this buffer cutted in two middle equal parts.

Taking inspiration from BufferingAudioSource code I’m trying to create a Thread that checks if it can save data to the disk.

This thread is instanciated inside the Writer constructor.
I’m sure the Writer is doing the right things (writing to disk without the background thread works fine), but I am also sure that there are mistakes around the notify stuff inside the writer and the thread. :oops:
The resulting audio presents cracks and miss original sections of data.

Here it is the run method.

  void run()
    while (! threadShouldExit())
      bool busy = false;
      const ScopedLock sl (m_lock);
      if(m_pWriter != 0 && m_pWriter->ShouldBeginWrite())
        busy = true;

In the writer code, after updating the buffer positions every time is called a StoreSlice method from the plugin filter, i do this calls:

   m_bShouldWrite = bLetsWrite;

 XRPWriterThread* pThread =  XRPWriterThread::getInstanceWithoutCreating();

The thread inherits from DeleteAtShutdown and Thread juce classes.

I hope someone thead expert could give me advice.