默认状况下exe不一样实例使用copy-on-write技术避免共享数据,好比运行了两个exe,最开始它们使用的都是一份虚拟内存页,而后第一个实例修改了全局变量, 这时候COW就会复制那一页,而后将第一个进程地址空间对应页映射到新复制的页,第二个实例保持映射老的页。 可是若是真的须要多个实例共享数据,好比计算有多少个exe程序正在运行,就能够使用该技术。app
使用MSVC提供的code
#pragma date_seg("xx")
能够在.obj中定义一个新的段,就像.data
.bss
.text
这种,而后为了多个exe实例共享该段,还须要通知连接器将该段设置为共享进程
#pragma comment(linker,"/SECTION:xx,RWS")
其中RWS
表示read write shared
,即指定该段共享。内存
示例代码以下:it
#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; }