# Read a tfile while writing with another process

**URL:** <https://root-forum.cern.ch/t/read-a-tfile-while-writing-with-another-process/18608>\
**Category:** ROOT\
**Created:** [December 12, 2014, 1:32pm UTC](https://root-forum.cern.ch/t/read-a-tfile-while-writing-with-another-process/18608 "2014-12-12T13:32:32Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![pcanal](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/pcanal/32/12439_2.png) [@pcanal](https://root-forum.cern.ch/u/pcanal)\
**Post date:** [January 28, 2015, 7:07am UTC](https://root-forum.cern.ch/t/read-a-tfile-while-writing-with-another-process/18608/6 "2015-01-28T07:07:34Z")

</div>

Hi,

The use of the non-default TObject::kOverwrite is fatal in this case. TObject::kOverwrite is an explicit to first remove the previous copy and then write the new copy (lightly in place of the hold one) into the file. This significantly increase the risk that the writing happens while the reader in not yet done reading.

If you want the write the object safely while still disabling the keeping of cycle (backup copy) use TObject::kWriteDelete (which write then deletes).

You can also use SaveSelf rather than Flush but then need to explicitly store each historgram.

```auto
#include "TFile.h"
#include "TH1F.h"

void writer() {
   TFile *f = new TFile("test.root","RECREATE");
   TH1F *h = new TH1F("h","h",100,-2,2);
   f->Write(0,TObject::kReadWrite);
   int count = 0;
   while(1) {
      printf("Loop %d\r",count++);
      fflush(stdout);
      h->FillRandom("gaus",100);
      h->Write(0,TObject::kReadWrite);
      f->SaveSelf();
      sleep(1);
   }
}

```

To refresh the information on the reader side, use ReadKeys:

```auto
void reading(const TFile *f, const char *name="gaus") {
   f->ReadKeys();
   delete f->FindObject(name);
   TH1F *h; f->GetObject(name,h);
   h->Draw();
}

```

Cheers,  
Philippe.

---

_[View the full topic](https://root-forum.cern.ch/t/read-a-tfile-while-writing-with-another-process/18608)._
