1

您好 StackOverflow 的用户。

我一直在使用 C++ 中 Win32 API 中的 MapViewOfFile,我是它的新手,但我一直在尝试为 mapview 文件创建一个信号量,所以一个实例无法复制到它,除非另一个实例有已经复制到它并且主实例已经读取它。



我得到的想法是创建不同的方法来做到这一点,但我需要知道最好的方法。

1)使用while循环等待mapviewfile为空。
我尝试执行以下操作:

mapViewFile = (LPTSTR) MapViewOfFile(mapView,
FILE_MAP_ALL_ACCESS,0,0,SH_MAX_MEMORY);

if(mapViewFile!=NULL){

// Wait for the mapviewfile to be empty.
while(mapViewFile!=""); // This while is only for delay the operation and wait for the mapviewfile it's empty, we don't need any action in this while.
CopyMemory((PVOID)mapViewFile,defaultalloc,(_tcslen(defaultalloc) * sizeof(TCHAR)));
UnmapViewOfFile(mapViewFile);
}

CloseHandle(mapView);

因此,当 mapviewfile 为空时,while 被跳过,“辅助”实例复制到其中,然后主实例读取它并清空 mapviewfile,这会生成一个信号量。

2)使用互斥锁
另一种方法是使用 Win32 Api 中的互斥锁,CreateMutex
我还没有使用过这个,但我想我可以用它来做我想做的事情。


所以,我的问题如下:

  1. 哪种方式最好做我想做的事?(在第 1 段中解释)
  2. mapviewfile 这样做没有问题吗?(请记住,我想与一个主实例通信两个或多个实例)。

就是这些问题,谢谢。

4

1 回答 1

1

您正在寻求同步对共享资源的访问。这样做的方法是使用同步对象。这意味着使用互斥锁。

Using a mutex means that you can do idle waiting rather than a busy loop. And you also don't need to concern yourself with the compiler optimising away the read of mapViewFile in the while loop. And if you have multiple processes writing then you've got a data race that you cannot resolve without a mutex or equivalent. Your first option can never work in that scenario.

Incidentally you would need to use strcmp in the while loop test. That's because mapViewFile!="" always evaluates true.

于 2013-04-13T15:31:29.620 回答