我试着编写一个小应用程序来熟悉用户空间中的写时复制的概念.我已经阅读了
answer by MSalters,并认为只有当我开始使用mmap的文件来存储我的数据时它才会起作用.因为我不需要基于文件的持久性,所以我尝试用共享内存做同样的事情.首先我mmap’ed并初始化了一个shm fd,然后我用MAP_PRIVATE映射了第二个副本并再次从中读取.然而,只需从中读取就会导致内核复制整个内容,花费更多时间并占用内存的两倍.为什么不做COW?
这是我提出的用于说明行为的程序:
#include
#include
#include
#include
#include
#include
static const size_t ARRAYSIZE = 1UL<<30;
void init(int* A)
{
for (size_t i = 0; i < ARRAYSIZE; ++i)
A[i] = i;
}
size_t agg(const int* A)
{
size_t sum = 0;
for (size_t i = 0; i < ARRAYSIZE; ++i)
sum += A[i];
return sum;
}
int main()
{
assert(sizeof(int) == 4);
shm_unlink("/cowtest");
printf("ARRAYSIZE: %lu\n", ARRAYSIZE);
int fd = shm_open("/cowtest", O_RDWR | O_CREAT | O_TRUNC, 0);
if (fd == -1)
{
perror("Error allocating fd\n");
return 1;
}
if (ftruncate(fd, sizeof(int) * ARRAYSIZE) == -1)
{
perror("Error ftruncate\n");
return 1;
}
/* Open shm */
int* A= (int*)mmap(NULL, sizeof(int) * ARRAYSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (A == (int*)-1)
{
perror("Error mapping A to memory\n");
return 1;
}
init(A);
/* Create cow copy */
int* Acopy = (int*)mmap(NULL, sizeof(int) * ARRAYSIZE, PROT_READ, MAP_PRIVATE, fd, 0);
if (Acopy == (int*)-1)
{
printf("Error mapping copy from file\n");
return 1;
}
/* Aggregate over A */
size_t sumA = agg(A);
size_t expected = (ARRAYSIZE * (ARRAYSIZE - 1)) >> 1;
assert(expected == sumA);
/* Aggregate over Acopy */
size_t sumCopy = agg(Acopy);
assert(expected == sumCopy);
shm_unlink("/cowtest");
printf("Enter to exit\n");
getchar();
return 0;
}
我用g -O3 -mtune = native -march = native -o shm-min shm-min.cpp -lrt编译它.
它创建的数组包含4GB的整数值.在终止程序之前,然后分配8GB的共享内存,在/ proc /< pid> / smaps中,您可以看到它在只读操作期间实际上执行了完整拷贝.我不知道为什么会那样做.这是内核错误吗?或者我错过了什么?
非常感谢任何见解.拉尔斯
编辑
这是Ubuntu 14.04(3.13.0-24)上/ proc /< pid> / smaps的相关内容:
7f3b9b4ae000-7f3c9b4ae000 r--p 00000000 00:14 168154 /run/shm/cowtest (deleted)
Size: 4194304 kB
Rss: 4194304 kB
Pss: 2097152 kB
Shared_Clean: 0 kB
Shared_Dirty: 4194304 kB
Private_Clean: 0 kB
Private_Dirty: 0 kB
Referenced: 4194304 kB
Anonymous: 0 kB
AnonHugePages: 0 kB
Swap: 0 kB
KernelPageSize: 4 kB
MMUPageSize: 4 kB
Locked: 0 kB
VmFlags: rd mr mw me sd
7f3c9b4ae000-7f3d9b4ae000 rw-s 00000000 00:14 168154 /run/shm/cowtest (deleted)
Size: 4194304 kB
Rss: 4194304 kB
Pss: 2097152 kB
Shared_Clean: 0 kB
Shared_Dirty: 4194304 kB
Private_Clean: 0 kB
Private_Dirty: 0 kB
Referenced: 4194304 kB
Anonymous: 0 kB
AnonHugePages: 0 kB
Swap: 0 kB
KernelPageSize: 4 kB
MMUPageSize: 4 kB
Locked: 0 kB
VmFlags: rd wr sh mr mw me ms sd