PDA

View Full Version : lock a file



Malek
27th December 2010, 23:27
Hi,

While writing on a file from some QThread and another thread try to write on the same file, The code will crash.

I need to lock the file until my thread finish writing on it. Then unlock it.
I mean by "lock" : prevent other threads from writing on this file until this thread finish writing on it.

May you help me.

Regards,

nroberts
27th December 2010, 23:38
Hi,

While writing on a file from some QThread and another thread try to write on the same file, The code will crash.

I need to lock the file until my thread finish writing on it. Then unlock it.
I mean by "lock" : prevent other threads from writing on this file until this thread finish writing on it.

May you help me.

Regards,

What you are looking for is called a "mutex". I could point to it in the documents but what you really want to do is do a web search and read more about programming in threads both generically and with the specific API provided by Qt.

squidge
27th December 2010, 23:44
If you don't care about other processes being able to write to your file (only other threads in your application), then you should use flock(). Your first thread will lock, write to the file, and then unlock. If another thread attempts during the write, it will block (at the flock() call) until the write is finished and the file is unlocked. Alternatively, you could create a file "filename.lock" which your second thread could detect, but the flock call is preferred as its done in the kernel.

This would also work if you have multiple copies of your application running, but it will not stop other applications from writing to your file unless they also use flock()

EDIT: Note that flock does not, typically, work across a networked mount point. I don't know if your file is local or remote. If you require that, I would suggest fctl, but you'll need to check what the server supports first.