In each thread, whenever you want access to the file:
- Before accessing the file, using the Windows API, create a named mutex (giving it the whole path to your file, case sensitive) and acquire it.
- Using C++ standard IO, open the file.
- Using C++ standard IO, write to the file.
- Using C++ standard IO, close the file.
- Release (don't destroy) the mutex
This is the most basic threading pattern - locking. It has
serious disadvantages (performance wise), since threads are locked waiting for the mutex, so in fact your program is no longer multithreaded.
Another pattern:
- Create a thread whose only purpose will be managing access to the file.
- Create a queue of commands (you may use the STL std::queue); this queue should be self-locking.
- Whenever a client wants to write someting to the file, add a 'please write' command to the queue.
- Have your file access pop commands from the queue, and execute them one by one.
- Whenever a client wants to read something from the file, add a 'read' command to the queue.
- The 'read' command should include a callback (pointer to interface, usually) to execute when the 'read' command is popped from the queue and executed.
This is more elaborate, and less blocking.
In general,
do not try to write multi threaded code until you have read at least 400 pages (that's one book, or a lot of articles) about multi threading design. You may google: 'lock free multi threading patterns', 'windows threads', 'parallel programming'.
Hope this helps,