默认情况下exe不同实例使用copy-on-write技术避免共享数据,比如运行了两个exe,最开始它们使用的都是一份虚拟内存页,然后第一个实例修改了全局变量,
这时候COW就会复制那一页,然后将第一个进程地址空间对应页映射到新复制的页,第二个实例保持映射老的页。
但是如果真的需要多个实例共享数据,比如计算有多少个exe程序正在运行,就可以使用该技术。
使用MSVC提供的
#pragma date_seg("xx")
可以在.obj中定义一个新的段,就像.data
.bss
.text
这种,然后为了多个exe实例共享该段,还需要通知链接器将该段设置为共享
#pragma comment(linker,"/SECTION:xx,RWS")
其中RWS
表示read write shared
,即指定该段共享。
示例代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <stdio.h>
#pragma data_seg("sharedvars")
volatile unsigned int counter = 0;
#pragma data_seg()
#pragma comment(linker,"/SECTION:sharedvars,RWS")
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PTSTR, int) {
InterlockedExchangeAdd(&counter, 1);
char cbuf[255];
sprintf(cbuf,"There are %d app instances.",counter);
MessageBox(NULL, cbuf, TEXT("Counting how many running application instances"), MB_ICONINFORMATION | MB_OK);
InterlockedExchangeSubtract(&counter, 1);
return 0;
}