我有 3 个程序,每个程序都需要在一个文件中写入 1000 次。 Mutex 必须在每 10 次写入后切换程序
#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();
}
第一个程序为“f1 << 1”,第二个程序为“f1 << 2” 它们不同步,如何实现? 请帮助我开始使用 2 个程序。
最佳答案
从您的描述中并不清楚您希望程序如何运行。您希望程序保证进程交替进行吗?如果是这样,您是否希望采用循环类型排序(例如,进程 1,然后是进程 2,然后是进程 3,然后再次是进程 1)?
但是,很明显您当前的互斥量使用不正确。首先,至少有一个进程必须调用 CreateMutex()
来实际创建互斥锁(否则没有可打开的互斥锁)。由于 CreateMutex()
的文档说:
If
lpName
matches the name of an existing named mutex object, this function requests theMUTEX_ALL_ACCESS
access right.
假设请求更多访问权限对您来说不是问题(很少有),那么您可以让所有实例调用 CreateMutex()
确保它们都共享相同的互斥量,并以实际先开始的为准创建是。
这是一个简单的示例,其中的进程以不可预测的顺序交替(允许重复),但连续 10 次正确写入文件而不会被并发写入者中断。
#include <Windows.h>
#include <conio.h>
#include <iostream>
#include <fstream>
int main ( int, char ** )
{
// get a named mutex. open the same mutex as other
// concurrent instances.
const ::HANDLE mutex = ::CreateMutexW(0, FALSE, L"Fubar");
if (mutex == INVALID_HANDLE_VALUE)
{
const ::DWORD error = ::GetLastError();
std::cerr
<< "Could not open mutex (" << error << ")."
<< std::endl;
return (EXIT_FAILURE);
}
// open the input file. notice the flags, you need to make
// sure the 2nd process doesn't overwrite whatver the first
// wrote, etc.
std::ofstream file("foo.txt", std::ios::app);
if (!file.is_open())
{
std::cerr
<< "Could not open file."
<< std::endl;
return (EXIT_FAILURE);
}
// wait for user to unblock after launch. this gives time
// to start concurrent processes before we write to the
// file.
::getch();
// not sure how your application goes, but lets just
// repeatedly write to the file until we're fed up.
for (int j=0; j < 100; ++j)
{
// lock the mutex around the code that writes to the
// file in a loop.
::WaitForSingleObject(mutex, INFINITE);
for (int i=0; i < 10; ++i) {
file << "process " << ::GetCurrentProcessId() << std::endl;
}
::ReleaseMutex(mutex);
// slow down so the application doesn't finish before we
// unblock concurrent instances.
::Sleep(100);
}
// don't forget to clean up!
::CloseHandle(mutex);
}
启动此进程的多个实例(2 个或更多),当所有实例启动后,在每个控制台窗口中按一个键让进程开始写入。输出文件将包含每个进程的 10 个输出。
关于c++ - 如何使用互斥量自动交换 3 个进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9034073/