共享内存

最后更新于:2022-04-02 04:03:22

[TOC] ## 共享内存 - 不同进程之间内存空间是独立的,也就是说进程不能访问也不会干扰其他进程的内存 - 如果两个进程希望通过共享内存的方式通信,可以通过`mmap()`系统调用实现 - 共享内存是效率最高的进程间通讯机制,因为数据不需要在内核和程序之间复制 ### go 实现
shm_writer.go ``` package main /* #cgo linux LDFLAGS: -lrt #include #include #include #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) int my_shm_new(char *name) { shm_unlink(name); return shm_open(name, O_RDWR|O_CREAT|O_EXCL, FILE_MODE); } */ import "C" import ( "fmt" "unsafe" ) const SHM_NAME = "my_shm" const SHM_SIZE = 4 * 1000 * 1000 * 1000 type MyData struct { Col1 int Col2 int Col3 int } func main() { fd, err := C.my_shm_new(C.CString(SHM_NAME)) if err != nil { fmt.Println(err) return } C.ftruncate(fd, SHM_SIZE) ptr, err := C.mmap(nil, SHM_SIZE, C.PROT_READ|C.PROT_WRITE, C.MAP_SHARED, fd, 0) if err != nil { fmt.Println(err) return } C.close(fd) data := (*MyData)(unsafe.Pointer(ptr)) data.Col1 = 100 data.Col2 = 876 data.Col3 = 8021 } ```

shm_reader.go ``` package main /* #cgo linux LDFLAGS: -lrt #include #include #include #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) int my_shm_open(char *name) { return shm_open(name, O_RDWR, FILE_MODE); } */ import "C" import ( "fmt" "unsafe" ) const SHM_NAME = "my_shm" const SHM_SIZE = 4 * 1000 * 1000 * 1000 type MyData struct { Col1 int Col2 int Col3 int } func main() { fd, err := C.my_shm_open(C.CString(SHM_NAME)) if err != nil { fmt.Println(err) return } ptr, err := C.mmap(nil, SHM_SIZE, C.PROT_READ|C.PROT_WRITE, C.MAP_SHARED, fd, 0) if err != nil { fmt.Println(err) return } C.close(fd) data := (*MyData)(unsafe.Pointer(ptr)) fmt.Println(data) } ```

';