在Go中通过Mmap将数组映射到文件 [英] Mapping an array to a file via Mmap in Go

查看:580
本文介绍了在Go中通过Mmap将数组映射到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过Mmap将数组映射到文件,数组可以是任何类型,如float64。在C中,我找到这个一个。阅读了一些文章后,我写了这篇示例。我不知道它是否正确,并且不会将值写入文件。如果我增加阵列的大小,例如从1000到10000,它会崩溃。如果有人知道如何以正确的方式做到这一点,请告诉我。

谢谢!

解决方案

例如,修改您的示例程序,

  package main 


fmt
os
系统调用
不安全


func main(){
const n = 1e3
t:= int(unsafe.Sizeof(0))* n

map_file,err:= os.Create(/ tmp / test.dat)
if err!= nil {
fmt.Println(err)
os.Exit(1)
}
_,err = map_file.Seek(int64(t -1),0)
if err!= nil {
fmt.Println(err)
os.Exit(1)
}
_,err = map_file .Write([] byte())
if err!= nil {
fmt.Println(err)
os.Exit(1)
}

mmap,err:= syscall.Mmap(int(map_file.Fd()),0,int(t),syscall.PROT_READ | syscall.PROT_WRITE,syscall.MAP_SHARED)
if err!= nil {

map_array:=(* [n] int)(unsafe.Pointer(& mmap [0]))

for i:= 0;我< N; i ++ {
map_array [i] = i * i
}

fmt.Println(* map_array)

err = syscall.Munmap(mmap)
if err!= nil {
fmt.Println(err)
os.Exit(1)
}
err = map_file.Close()
if err!= nil {
fmt.Println(err)
os.Exit(1)
}
}


I'm trying to map an array to a file via Mmap, the array could be any type, like float64. In C, I find this one. After reading some texts, I wrote this sample. I don't know if it is correct, and it is not writing the values to the file. If I increase the size of array a lot, e.g from 1000 to 10000, it crashes. If someone know how to do that in the correctly way, please, tell me.

Thanks!

解决方案

For example, revising your sample program,

package main

import (
    "fmt"
    "os"
    "syscall"
    "unsafe"
)

func main() {
    const n = 1e3
    t := int(unsafe.Sizeof(0)) * n

    map_file, err := os.Create("/tmp/test.dat")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    _, err = map_file.Seek(int64(t-1), 0)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    _, err = map_file.Write([]byte(" "))
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    mmap, err := syscall.Mmap(int(map_file.Fd()), 0, int(t), syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    map_array := (*[n]int)(unsafe.Pointer(&mmap[0]))

    for i := 0; i < n; i++ {
        map_array[i] = i * i
    }

    fmt.Println(*map_array)

    err = syscall.Munmap(mmap)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    err = map_file.Close()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

这篇关于在Go中通过Mmap将数组映射到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆