0

I have the following situation:

There are a thousand processes and each of them has the following task:

  • 1) choose a nr X from 1 to 1 000

  • 2) if X.txt does exists, go to (1)

  • 3) Open X.txt and write "hello this is process_id".

Now, my question is, if I use open('X.txt', 'wx') is it possible that at some point 2 processes will be able to open the file the same time, because they will at the same time say: "ok, X.txt doesnt exist, so lets open it for writing"?

If it is possible, is there a safety mechanism I could use, for example when I close the file, check if I was the only process that was writing to this file?

  • You need to learn about [file locking](https://en.wikipedia.org/wiki/File_locking). There are some examples in [this question](https://stackoverflow.com/questions/489861/locking-a-file-in-python). – larsks Oct 12 '18 at 02:18
  • I think it's fine, since it's called "exclusive" creation. Only problem is that by doing it, only one process is able to log its greeting "hello this is process ..." in each file, that is, the process which creates the file. Another process coming later simply raises an exception, instead of logging its own greeting in another line. By the way, don't forget to handle the `FileExistsError` exception. – Zheng Liu Oct 12 '18 at 03:28

1 Answers1

0

Since you're always using the x flag to open, you're safe and don't have to worry about anything else. Only one process (the one that actually created the file) will succeed at opening it.