2012-01-27 26 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