如何在互斥锁中进行循环类型排序
How to make a round-robin type ordering in a mutex?
#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
,它们是有效的,但我需要一个循环类型的排序。或者,至少,在没有按顺序两次写入一个进程的情况下。
我不认为你可以用一个互斥锁来实现你的目标,但你可以相当轻松地使用两个互斥锁来确保没有一个进程在一个序列中写入两次。您需要做的是始终有一个进程处于等待队列,一个进程处于写入状态。为此,您创建了两个多文本,我们称它们为 queueMutex
和 writeMutex
.伪代码中的迭代逻辑应如下所示:
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++ 中按预定义的顺序循环浏览类实例?
- 在C++中循环访问类继承
- 我想在 C++ 中使用 for 循环创建类对象
- 有没有办法重复循环循环?
- 您可以在没有列表或向量的情况下循环访问类对象吗?
- 虽然第三次循环循环,尽管在我眼中没有满足它的条件,因此打印了一个空字符串
- 循环依赖(类对类型定义,类型定义对类),前向声明给出不明确的调用
- 避免以不同的迭代剂的循环循环避免几乎相同的代码重复
- 循环循环保存到数组,然后访问;
- 对于循环循环仅 3 次
- 处理媒体循环循环循环通过向量中的对象的各个方面
- 将C转换为循环循环循环
- 嵌套的循环调用类成员函数
- 关于如何正确循环循环并找到最小的价值,需要基本C 的帮助
- C++ 长度为 100 的循环队列类
- 循环访问类的所有公共方法
- 循环访问类中的不同集合类型
- 如何在C++中使用循环依赖类
- 循环访问类模板的显式专用化