c++ - 如何在互斥锁中进行循环类型排序?

标签 c++ windows algorithm multiprocessing

#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 个 pograms ... 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)

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

关于c++ - 如何在互斥锁中进行循环类型排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9037762/

相关文章:

c++ - 检查是否有 TCP/IP 连接以及它是 WiFi 还是 3G - Windows Mobile 6.5 - C/C++

java - 使用 C++ 语法的 ANTLR 解析器示例

c# - P/从 c# 调用非托管 C++ 代码 - 获取 "tried to access protected memory error"

c++ - Microsoft 系统可执行拷贝差异

windows - 有没有办法强制Windows缓存文件?

c++ - 如何将 sqlite3_mprintf() 与 UTF-16 字符串一起使用?

c# - 远程管理应用程序中使用的技术(非RD)

algorithm - 三叉树与哈希表

c# - 如何优化这个次优的 Set-Cover 解决方案?

algorithm - 判断多用户编辑文本 "Owner"