Evening all been looking into an issue where multiply threads access a single file.
So basically I have one thread which open, writes and then closes the file. Then another thread which copies the file and deletes the file. From reading up by default fileIO is Synchronous.
However on occasion CopyFile fails with last error code of ERROR_SHARING_VIOLATION.
Just to make sure my understanding is correct of Synchronous is if one thread is writing to that file and the other thread has to wait for that write to finish?
The Windows file system, NTFS, is very slow. It's a transactional file system and the OS can be still messing around with the file long after the app has stopped using it.
If it says it's still in use, it's still in use. It's just an error you have to cope with.
You use a mutex, making all the worker threads waiting until the file is written.
In your particular case a semaphone is more appropiate to use (only one thread which write data needs exclusive access, readers does not need to wait each other)
Hey modoran thank you for your response, currently im trying to understand everything.
Just found when one thread is copying that file and another thread tries to write to that file at the same time it fail to write. I thought it being asynchronous it would wait at the write command till it has finished coping in the other thread.
Gone down the root of a named mutex does the job. Was playing around with them and found if I have one thread with waitforsingleobject with INFINITE set, eventually that thread halts as its waiting for the mutex to be the other thread which uses the same named mutex has released it and closed the handle and the thread still going.
Can the OS get backlogged has it has not released it?
When you want tyo access the file, put this code inside any threads, including the main thread:
1 2 3 4 5 6
EnterCriticalSection (&cs); // all other threads will be automatically blocked here
// access the file here, only one thread can run at this point
LeaveCriticalSection (&cs); // do not forget to release it or other threads will wait forever
Hey modoran thank you again for your help, what I like about the mutex is that if one thread cannot get the named mutex it jumps over that code and carrys on with something else instead of waiting, as that thread does other things.