3

How can I lock a file in windows to only current thread (no other threads from same process and no other processes) can access (read/write) the file?

If it is possible please tell me some fcntl-like solution (solution which locks file having its descriptor). But in any case other solutions are welcome too.

Mihran Hovsepyan
  • 10,810
  • 14
  • 61
  • 111

2 Answers2

5

In Windows, you can open a file with exclusive access with the API function CreateFile and specifying 0 as the share mode. More details at this MSDN link, and this MSDN link.

Chad
  • 18,706
  • 4
  • 46
  • 63
  • Much better than my solution +1 – Scott Chamberlain Jul 26 '11 at 16:06
  • If subsequent threads all use the `CreateFile` API (no passing of the returned file `HANDLE`), then the calls to `CreateFile` _should_ fail, if I understand the documentation correctly. However, I've not tried to do this (inter-thread) specifically. – Chad Jul 26 '11 at 16:09
1

Use the WinAPI call LockFile, Here is a example of its use. However this will only protect you from other processes from touching your file, it still lets other threads in the same process use the file.

EDIT: I did not see this was C++ sorry, I only know the inter thread c# solution, however that MSDN link can at least get you started on preventing other processes from touching your file.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
  • 2
    Mihran: you can call that function from a C++ function. This is the Win32 C API. – rubenvb Jul 26 '11 at 16:02
  • Note that `LockFile` locks the file for exclusive use by a single process, but not by a single thread. To ensure the latter, you will have to build your own locking mechanism within the process. – Martin B Jul 26 '11 at 16:05