// Lock loads all memory pages in physical memory. This can take a long time for // larger files but access to these memory locations will be faster. func (m *Map) Lock() (err error) { if err := syscall.Mlock(m.Data); err != nil { return err } return nil }
func main() { flag.Parse() allocationSize := *allocationInGB * GB log.Printf("Allocating 0x%X bytes\n", allocationSize) memory := make([]byte, allocationSize) // mlock prevents memory from being swapped to disk err := syscall.Mlock(memory) if err != nil { log.Fatalln("Error locking memory.", err) } var value byte for { log.Printf("Writing 0x%X to 0x%X bytes.\n", value, allocationSize) for i, _ := range memory { memory[i] = value } log.Printf("Verifying %x written to %x bytes.\n", value, allocationSize) for i, v := range memory { if v != value { log.Printf("Found unexpected byte value 0x%X at position %d.\n", v, i) } } value++ } }
// Lock locks a region of the mapped shared memory func (buf *sharedBuffer) Lock(offset, length int) error { b := buf.Bytes() err := checkOffsetLength(b, offset, length) if err == nil { err = syscall.Mlock(b[offset : offset+length]) } return os.NewSyscallError("shm: mlock", err) }
func mmapFile(fileName string) (*mmapData, error) { file, err := os.Open(fileName) if err != nil { return nil, err } stat, err := file.Stat() if err != nil { file.Close() return nil, err } size := stat.Size() pageAlignedSize := (size + 4095) &^ 4095 data, err := syscall.Mmap(int(file.Fd()), 0, int(pageAlignedSize), syscall.PROT_READ, syscall.MAP_PRIVATE) if err != nil { file.Close() return nil, err } err = syscall.Mlock(data) if err != nil { syscall.Munmap(data) file.Close() return nil, err } md := &mmapData{file, data[:size]} runtime.SetFinalizer(md, func(m *mmapData) { syscall.Munlock(m.d) syscall.Munmap(m.d) m.f.Close() }) return md, nil }
// Lock implements Map.Lock(). func (m *mmap) Lock() error { return syscall.Mlock(m.data) }
// Prevent the mmap from being paged to the swap area. func (m Mmap) Lock() error { return syscall.Mlock(m) }