Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
go mmap example
package main
import (
"fmt"
"io/ioutil"
"os"
"syscall"
"unsafe"
)
func write() {
const n = 1e3
t := int(unsafe.Sizeof(int64(0))) * n
mapFile, err := os.Create("./mmap.dat")
if err != nil {
panic(err)
}
_, err = mapFile.Seek(int64(t-1), 0)
if err != nil {
panic(err)
}
_, err = mapFile.Write([]byte(" "))
if err != nil {
panic(err)
}
// 将文件操作映射为字节数组操作
mmap, err := syscall.Mmap(int(mapFile.Fd()), 0, t, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED)
if err != nil {
panic(err)
}
// 获取第一个字节的位置
mapArray := (*[n]int)(unsafe.Pointer(&mmap[0]))
for i := 0; i < n; i++ {
mapArray[i] = i * i
}
// 解除映射?数组和文件底层操作不再映射起来了?
err = syscall.Munmap(mmap)
if err != nil {
panic(err)
}
err = mapFile.Close()
if err != nil {
panic(err)
}
}
func read() {
const n = 1e3
b, err := ioutil.ReadFile("./mmap.dat")
if err != nil {
panic(err)
}
intArray := (*[n]int)(unsafe.Pointer(&b[0]))
for _, v := range *intArray {
fmt.Printf("%d\n", v)
}
}
func main() {
write()
read()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment