Golang 源碼閱讀 os.File

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

最近寫程式過程感覺golang讀寫檔案比較慢。因此決定讀一下源碼。

src/os/file.go

http://www.ieyebrain.com:8080/golang/src/os/file.go

中定義了file的函數:

    Name, Read,Write,Seek,Close等等。

例如:Read函數

func (f *File) Read(b []byte) (n int, err error) {
    if f == nil {
        return 0, ErrInvalid
    }
    n, e := f.read(b)
    if n == 0 && len(b) > 0 && e == nil {
        return 0, io.EOF
    }
    if e != nil {
        err = &PathError{"read", f.name, e}
    }
    return n, err
}

這裡實現了委託調用的介面技巧。就是把Read操作委託給f.read函數。f為File類型指標,找了一圈,才發現它定義在具體實現的檔案中。比如:file_windows.go中,

http://www.ieyebrain.com:8080/golang/src/os/file_windows.go

type File struct {
    *file
}
type file struct {
    fd      syscall.Handle
    name    string
    dirinfo *dirInfo   // nil unless directory being read
    l       sync.Mutex // used to implement windows pread/pwrite

    // only for console io
    isConsole bool
    lastbits  []byte // first few bytes of the last incomplete rune in last write
    readbuf   []rune // input console buffer
}

下面是讀取的正主,syscall.Read(f.fd,b)。 File -> file -> syscall -> WindowsAPI

多了三次調用,File -> file是實現跨平台。 file 這一層加了一個鎖。這個可能是一個大的消耗。這個鎖是為了統一的操作語義,在Unix平台上,並沒有這個鎖。

func (f *File) read(b []byte) (n int, err error) {
    f.l.Lock()
    defer f.l.Unlock()
    if f.isConsole {
        return f.readConsole(b)
    }
    return fixCount(syscall.Read(f.fd, b))
}

調用過程:

1 http://www.ieyebrain.com:8080/golang/src/syscall/syscall_windows.go

func Read(fd Handle, p []byte) (n int, err error)  -> ReadFile

2 http://www.ieyebrain.com:8080/golang/src/syscall/zsyscall_windows.go

func ReadFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error)

3 http://www.ieyebrain.com:8080/golang/src/runtime/syscall_windows.go

func syscall_Syscall6(fn, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) {
    c := &getg().m.syscall
    c.fn = fn
    c.n = nargs
    c.args = uintptr(noescape(unsafe.Pointer(&a1)))
    cgocall(asmstdcallAddr, unsafe.Pointer(c))
    return c.r1, c.r2, c.err
}

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.