Julian
Julian

Reputation: 503

Does VirtualFree unlock VirtualLock?

I was rewriting pretty old c++ code and stumbled about the memory management part.

More specific, Memory "needed" was first allocated in a fashion similar to

int* Buffer;
int numPoints=80000;
Buffer = (int*)VirtualAlloc(NULL, numPoints* sizeof(int), MEM_COMMIT, PAGE_READWRITE);
VirtualLock(Buffer,numPoints * sizeof(int));

However, the Buffer was only released using VirtualFree, not VirtualUnlock.

So, first question: Is VirtualFree calling VirtualUnlock?

Furthermore I read a bit about VirtualLock. In my code, it is apparently used for increasing performance, since a lot of very large arrays are used and accessed pretty frequently, partly even to be drawn as a graph with 2 fps or so... However, I read that 1. Virtuallock can decrease system performance, in the end slowing everything down again and 2. Virtuallock isn't really increasing performance for large buffers. The latter statement was tested here with the strassen HBC ( https://software.intel.com/de-de/forums/intel-threading-building-blocks/topic/276995 ).

So, concluding I would decide against VirtualLock, however https://msdn.microsoft.com/de-de/library/windows/desktop/aa366895(v=vs.85).aspx states that VirtualLock is ensuring that subsequent access to the region will not incur a page fault. Does this mean, commenting out VirtualLock will make access like *(buffer+10)=1 fail or produce a page fault (provided buffer has more than 11 allocated points)?

So second question is: can I safely discard locking memory without putting array access to danger of page faults or crashes?

Upvotes: 1

Views: 1072

Answers (1)

Mari MIsato
Mari MIsato

Reputation: 41

Yes it is. VirtualFree(MEM_RELEASE/MEM_DECOMMIT) unlocks the region if it had been locked with VirtualLock().

And VirtualLock() is still useful because it makes more faster access. (Furthermore, some of the tasks needs the non-paged memory as like overlapped IO.) Without VirtualLock(), over hundres megs bytes buffers are not guaranteed to be non-paged regardless of the physical memory size, because the O.S tends to preserve physical memory for the Kernel's non-paged pool & IO cache.

By the way, you need to SetProcessWorkingSetSize() to secure physical memory for your own process. VirtualLock() could fail without enough process working set.

IMHO it's not a good idea to lock the huge memory region for the general purpose software(running on various system with unknown system memory size) because it's stealing physical memory from the critical part of the O.S. Use it for the software that is running on the dedicated machine(as like the dedicated server, or dedicated encoding PC).

Upvotes: 4

Related Questions