Why does it not create many threads when many goroutines are blocked in writing file in golang?

后端 未结 3 643
盖世英雄少女心
盖世英雄少女心 2020-12-05 16:01

As we know in go, a thread may be created when the goroutine has to perform a blocking call, such as a system call, or a call to a C library via cgo. Some test code:

3条回答
  •  醉酒成梦
    2020-12-05 16:48

    The issue 4056 discusses how to limit the number of actual threads (not goroutine) created.

    Go 1.2 introduced that thread limit management in commit 665feee.

    You can see a test to check if the number of thread created is actually reached or not in pkg/runtime/crash_test.go#L128-L134:

    func TestThreadExhaustion(t *testing.T) {
        output := executeTest(t, threadExhaustionSource, nil)
        want := "runtime: program exceeds 10-thread limit\nfatal error: thread exhaustion"
        if !strings.HasPrefix(output, want) {
            t.Fatalf("output does not start with %q:\n%s", want, output)
        }
    }
    

    That same file has an example to create an actual thread (for a given goroutine), using runtime.LockOSThread():

    func testInNewThread(name string) {
        c := make(chan bool)
        go func() {
            runtime.LockOSThread()
            test(name)
            c <- true
        }()
        <-c
    }
    

提交回复
热议问题