Problems with TFile when using TThread and TMutex

Dear rooters,
I have a problem with TFile and threads.
I’m developing a software to perform the data processing in order to provide on-line monitoring.
I have basically four classes:

1- a data processor (cRunAnalyzer)
2- the current event class (cEvent)
3- a collection of histograms (cHisto)
4- a GUI (NMGui)

The class cRunAnalyzer contains a TThread for the data readout and processing and the GUI is in a separated thread (a TApplication is started at the beginning) so I use a global mutex (TMutex) to provide the correct Locking and Unlocking of the resources.

The analysis thread is mainly calling this method:

int cRunAnalyzer::AnalyzeCurrentFile(int board_id){
...
//open input binary file:
  FILE *infile = fopen(Form("%s",fname),"rb");

//open output TFile
  fout = new TFile(Form("%s/%s.root",outpath,currentfile_name),"RECREATE");
    if (fout->IsZombie()){printf ("\n\nProblems with output file\n\n"); return-1;}

//create output tree
  tree = new TTree(Form("mg%d",board_id),Form("mg%d",board_id));
  tree->Branch("cEvent","cEvent",&evt);
  tree->BranchRef();

//Loop over all the binary file
while (1){
   //read binary data
   //process data

   mutex->Lock();
   //Fill histos in cHistos
   mutex->UnLock();

   //fill output tree
   mutex->Lock();  
   fout->cd();
   tree->Fill();
   mutex->UnLock();

   //write tree to file
   if ((nneevv%50000)==0){
     TThread::Printf("Run_id=%d: File_id=%d File_name=%s - AUTOSAVING at event %ld",run_id, currentfile_id, fname, nneevv);
     mutex->Lock();  
     fout->cd();
     tree->Write("",TObject::kOverwrite);
     mutex->UnLock();
   }
}

...

//at the end close the output file:
mutex->Lock();  
fout->Close();
mutex->UnLock();  

return 0;
}

The GUI has accesss to cHistos for drawing the histograms it contains. For this reason the Draw call is protected like this:

//In the GUI
mutex->Lock();  
theHistos->GetHisto1D(xx)->Draw();
mutex->UnLock();

Things work fine but if the GUI tries to lock the mutex when the analysis thread is closing the output file (i.e. just before fout->Close()) it starts waiting an infinite time. The program does not crash but it stucks waiting some never happening unlock. The strange thing is that the same happens if fout->Close() is not protected by mutex->Lock()/UnLock().

Any suggestion?

Thanks

Tommaso