N
N
nano_e_t_42017-10-10 22:59:33
go
nano_e_t_4, 2017-10-10 22:59:33

How do goroutines work?

I read the doc, read the habr, then re-read it again and still did not understand:

package main
import (
"fmt"
"os"
)

func writeToFile() {
    file, err := os.Create("result.txt")
    if err != nil {
        fmt.Println("Cannot create file")
    }
    defer file.Close()

    fmt.Fprintf(file, "Hello Readers of golangcode.com")
}

func main() {
    go writeToFile()
    for {}
}

after all, in theory, the result.txt file with the corresponding entry should turn out. but it is not there (
and if I change the infinite loop to time.wait, then the file appears
like in any case, control should be transferred to the newly arisen goroutine
, please explain why it happens like this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2017-10-10
@nano_e_t_4

Go has such a system variable as $GOMAXPROCS, by default it is equal to the number of processor cores. Its value determines how many processes will be started by the Go scheduler. Goroutines are shared between these processes. If one goroutine has taken all the computational time of one process (as in your case, an infinite for loop, because it is not interrupted by I / O operations or other cases of waiting for resources), then if $GOMAXPROCS=1, other goroutines will wait for the release of a single process.
When you change the loop to a timer, the moment time.Wait is called, the process is released and can execute another goroutine.

R
rustler2000, 2017-10-10
@rustler2000

https://github.com/golang/go/issues/17174

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question