Created
July 10, 2020 13:50
-
-
Save g10guang/3dc5fda81684acda87ff10510e4d804a to your computer and use it in GitHub Desktop.
go mmap example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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