Reputation: 1
Is there, on Windows, any easy way to lock a file in an exclusive way (reading and writing for my software) in multithread C code? I've tried the LockFileEx but it works only between process and not for thread(of the same process).
Note: My problem is that i've made a little file server(multithread), when a request for a file comes, one thred "A" must acces in exclusive way to the requested "file1.txt", but if another thread "B" wants the same "file1.txt" it has to wait before to use this file. If Thread "A" uses the CreateFile() with dwSharedMode to "0" for open/create "file1.txt", ensures that only it read or open this file, infact error happens if thread "B" tries to open the "file1.txt". Now how thread "B" can wait on "file1.txt"?
Upvotes: 0
Views: 1730
Reputation: 4025
I understand you question as the following one : how to organize access to the resource(file) for mutliply threads(readers - writers problem should be solved).
If your resource should be shared amoung threads that operate within the same process:
use synchronization primitive critical_section
(it is more efficient than system objects synchronization primitives, but works only for threads within the same process)
otherwise use mutex
;
Upvotes: 1
Reputation: 498
Slim Reader/Writer (SRW) Locks
SRW locks provide two modes in which threads can access a shared resource:
Shared mode, which grants shared read-only access to multiple reader threads, which enables them to read data from the shared resource concurrently. If read operations exceed write operations, this concurrency increases performance and throughput compared to critical sections.
Exclusive mode, which grants read/write access to one writer thread at a time. When the lock has been acquired in exclusive mode, no other thread can access the shared resource until the writer releases the lock.
Upvotes: 0
Reputation: 25705
You can open the file in exclusive mode by setting dwShareMode
to 0
in CreateFile()
function.
Read more here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa363874(v=vs.85).aspx
Upvotes: 1