从不同的goroutines制作昂贵的系统调用是否有意义?

Vit*_*aev 8 multithreading system-calls go goroutine

如果应用程序使用多个文件描述符(例如,打开 - 写入数据 - 同步 - 关闭)进行了一些繁重的工作,那么Go运行时会发生什么?当昂贵的系统调用发生时(例如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()
}
Run Code Online (Sandbox Code Playgroud)

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

小智 4

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

\n\n

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

\n