July 18th Wednesday (七月 十八日 水曜日)

  Locking a region of memory is as simple as calling mlock with a pointer to the start
of the region and the region’s length. Linux divides memory into pages and can lock
only entire pages at a time; each page that contains part of the memory region speci-
fied to mlock is locked.The getpagesize function returns the system’s page size,which
is 4KB on x86 Linux.

  For example,to allocate 32MB of address space and lock it into RAM,you would
use this code:

const int alloc_size = 32 * 1024 * 1024;
char* memory = malloc (alloc_size);
mlock (memory, alloc_size);

  Note that simply allocating a page of memory and locking it with mlock doesn’t
reserve physical memory for the calling process because the pages may be copy-on-write.
Therefore,you should write a dummy value to each page as well:

size_t i;
size_t page_size = getpagesize ();
for (i = 0; i < alloc_size; i += page_size)
  memory[i] = 0;

  The write to each page forces Linux to assign a unique, unshared memory page to the
process for that page.

  To unlock a region,call munlock,which takes the same arguments as mlock.

  If you want your program’s entire address space locked into physical memory,call
mlockall.This system call takes a single flag argument:MCL_CURRENT locks all currently
allocated memory,but future allocations are not locked;MCL_FUTURE locks all pages that
are allocated after the call.Use MCL_CURRENT|MCL_FUTURE to lock into memory both
current and subsequent allocations.

  Locking large amounts of memory, especially using mlockall, can be dangerous to
the entire Linux system. Indiscriminate memory locking is a good method of bringing
your system to a grinding halt because other running processes are forced to compete
for smaller physical memory resources and swap rapidly into and back out of memory
(this is knownas thrashing).If you lock too much memory,the system will run out of
memory entirely and Linux will start killing off processes.

  For this reason, only processes with superuser privilege may lock memory with
mlock or mlockall.If a nonsuperuser process calls one of these functions,it will fail,
return -1,and set errno to EPERM.

  The munlockall call unlocks all memory locked by the current process,including
memory locked with mlock and mlockall.

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值