2012-01-27 50 views
1
#include "stdafx.h" 
#include <Windows.h> 
#include <conio.h> 
#include <fstream> 
#include <iostream> 
using namespace std; 

int main (int, char **) 
{ 
    HANDLE mutex = CreateMutex(NULL, FALSE, L"PRV"); 

    for (int j=0; j < 100; ++j) 
    { 
     WaitForSingleObject(mutex, INFINITE); 

     ofstream file("c:\\write.txt", ios::app); 
     for (int i=0; i < 10; ++i) { 
      file << 1; 
     } 
     ReleaseMutex(mutex); 
     Sleep(100); 
    } 

    CloseHandle(mutex); 
} 

创建4个pograms与file << 1 ...... file << 4和他们的作品,但我需要一个循环型排序。或者,至少,没有连续两次写入一个进程。如何在互斥体中进行循环类型排序?

+1

在[这个答案](http://stackoverflow.com/a/9036076/1168156)到你以前的问题André已经告诉你如何通过使用名称互斥来同步进程,但是你确定它是你想要的吗?我想如果你只是在同一个进程中创建4个线程将会容易得多。 – LihO 2012-01-27 18:45:46

+0

@Artem:您可能想要指定“程序”实际上是单独的进程。这将有助于人们提供更合适的答案。 – 2012-01-30 16:37:37

回答

1

我不认为你可以用一个互斥体实现你的目标,但你可以很容易地使用两个互斥体来确保没有一个进程在一个序列中写入两次。你需要做的是始终让一个进程处于等待队列中,一个进程处于写入状态。为此,您创建两个互斥体,我们称之为queueMutexwriteMutex。伪代码中的迭代逻辑应如下所示:

acquire(queueMutex) // The process is next to write 
acquire(writeMutex) // The process can now write 
release(queueMutex) // Some other process can enter the queue 

// now we can write 
write_to_file() 

// Let's hold on here until some other process 
// enters the queue 
// we do it by trying to acquire the queueMutex 
// until the acquisition fails 
while try_acquire(queueMutex) 
    release(queueMutex) 
    sleep 

// try_acquire(queueMutex) finally failed 
// this means some other process has entered the queue 
// we can release the writeMutex and finish this iteration 
release(writeMutex) 

我会将实现细节留给您。当你实现算法时,确保你正确处理最后一个过程的最后一次迭代,否则它会挂起。祝你好运!

+0

我也非常肯定这种方法可以扩展到用N个互斥体实现N个进程的循环迭代。只需要有一个互斥队列,并确保每个进程通过获取下一个互斥锁,释放旧互斥锁,然后等待以确保旧互斥体在继续之前被另一个进程选中。 – 2012-02-04 07:25:42