從您的描述中確切地說明您希望程序的行爲如何。你是否希望程序保證進程是交替進行的,如果是這樣,你是否需要循環類型排序(例如,進程1,然後進程2,然後進程3,然後再進程1)?
但是,很明顯,您當前的互斥鎖使用不正確。首先,至少有一個進程必須調用CreateMutex()
才能真正創建互斥鎖(否則不會有互斥鎖打開)。由於爲CreateMutex()
的文件說:
如果lpName
現有命名互斥對象的名稱相匹配,此功能要求MUTEX_ALL_ACCESS
訪問權限。
假設請求更多的訪問是不是對你的問題(事實上並非如此),那麼你可以擁有所有實例調用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個輸出的burts。
你忘了提及這是家庭作業及你的努力來解決它。 – 2012-01-27 13:42:19
我不認爲這是作業;一位教授會知道(我希望!)一個互斥體不能像這樣工作。 – MSalters 2012-01-27 14:17:55
@ MSalters:並不意味着學生理解這個概念以及他們的教授;-) – 2012-01-27 15:04:58