I have 3 programs, each of them need to write 1000 times in one file. Mutex must switch programs after every 10 writings
#include "stdafx.h"
#include <Windows.h>
#include <fstream>
#include <iostream>
using namespace std;
HANDLE ghMutex;
void write()
{
ghMutex = OpenMutex(SYNCHRONIZE, false, (LPTSTR)"WriteData");
for (int i=0; i<100; i ++) {
WaitForSingleObject(ghMutex, INFINITE);
ofstream f1("c:\\write.txt", ios_base::app);
for (int j=0; j<10; j++)
f1 << 2;
ReleaseMutex(ghMutex);
f1.close();
Sleep(100);
}
}
void main(){
write();
}
First program with "f1 << 1" and second with "f1 << 2" They aren't synchronize, how to make it? Help me to do it with 2 programs for beginning, please.
It's not clear from your descriptions exactly how you want your program to behave. Do you want the program to guarantee that the processes alternate, if so, do you want a round-robin type ordering (e.g. process 1, then process 2, then process 3, then process 1 again)?
However, it's clear that your current mutex usage is incorrect. First, at least one process must call
CreateMutex()
to actually create the mutex (or else there is no mutex to open). Since the documentation forCreateMutex()
says:Assuming requesting more access is not a problem for you (it rarely is), then you can just have all instances call
CreateMutex()
ensuring that they all share the same mutex and whichever starts first actually creates is.This is a simple example with processes that alternate in an unpredictable order (repeats are allowed), but correctly write to the file 10 times in a row without being interrupted by concurrent writers.
Start multiple instances of this process (2 or more) and when all are launched, press a single key in each console window to have the processes start writing. The output file will contain burts of 10 outputs for each process.
Is
ghMutex
valid in any of the processes ? What about the value returned byGetLastError()
afterOpenMutex()
andWaitForSingleObject()
?You need to create the mutex in one of the processes before other processes can open it. Fortunately,
CreateMutex
does exactly what you need: it creates the mutex if it does not exist, and opens it it if does.And you may want to close the stream before (not after) releasing the mutex, so that cached data is flushed before other processes start writing.