从不同的goroutine进行昂贵的系统调用是否有意义



如果应用程序使用多个文件描述符(例如,打开 - 写入数据 - 同步 - 关闭(执行一些繁重的工作,Go 运行时实际上会发生什么?它是否在发生昂贵的系统调用时阻止所有 goroutines(如 syscall.Fsync (?还是只有调用 goroutine 被阻止,而其他 goroutine仍在运行?

那么,使用多个工作线程编写程序来执行大量用户空间 - 内核空间上下文切换是否有意义?使用多线程模式进行磁盘输入是否有意义?

package main
import (
    "log"
    "os"
    "sync"
)
var data = []byte("some big data")
func worker(filenamechan chan string, wg *sync.waitgroup) {
    defer wg.done()
    for {
        filename, ok := <-filenamechan
        if !ok {
            return
        }
        // open file is a quite expensive operation due to
        // the opening new descriptor
        f, err := os.openfile(filename, os.o_create|os.o_wronly, os.filemode(0644))
        if err != nil {
            log.fatal(err)
            continue
        }
        // write is a cheap operation,
        // because it just moves data from user space to the kernel space
        if _, err := f.write(data); err != nil {
            log.fatal(err)
            continue
        }
        // syscall.fsync is a disk-bound expensive operation
        if err := f.sync(); err != nil {
            log.fatal(err)
            continue
        }
        if err := f.close(); err != nil {
            log.fatal(err)
        }
    }
}
func main() {
    // launch workers
    filenamechan := make(chan string)
    wg := &sync.waitgroup{}
    for i := 0; i < 2; i++ {
        wg.add(1)
        go worker(filenamechan, wg)
    }
    // send tasks to workers
    filenames := []string{
        "1.txt",
        "2.txt",
        "3.txt",
        "4.txt",
        "5.txt",
    }
    for i := range filenames {
        filenamechan <- filenames[i]
    }
    close(filenamechan)
    wg.wait()
}

https://play.golang.org/p/O0omcPBMAJ

如果系统调用阻塞,Go 运行时将启动一个新线程,以便可用于运行 goroutines 的线程数保持不变。

更全面的解释可以在这里找到:https://morsmachine.dk/go-scheduler

最新更新