如何在互斥锁中进行循环类型排序

How to make a round-robin type ordering in a mutex?

本文关键字:循环 循环类 类型 排序      更新时间:2023-10-16
#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);
}

我用 file << 1 创建了 4 个 pogram ...file << 4,它们是有效的,但我需要一个循环类型的排序。或者,至少,在没有按顺序两次写入一个进程的情况下。

我不认为你可以用一个互斥锁来实现你的目标,但你可以相当轻松地使用两个互斥锁来确保没有一个进程在一个序列中写入两次。您需要做的是始终有一个进程处于等待队列,一个进程处于写入状态。为此,您创建了两个多文本,我们称它们为 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)

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