L
L
LittleBuster2015-06-19 00:31:16
go
LittleBuster, 2015-06-19 00:31:16

Println, Scan and multithreading?

The question is this: after I type some word in the console and press Enter, it is printed only after the next delay for from the my function, along with the next number k, despite the fact that my is executed in a separate thread. How to output Println after scan-a without time delay? regardless of my

package main

import "fmt"
import "strconv"

func my() {
  var k int = 0
  for {
    for i:=0; i < 10000000000; i++ {
    }
    k++
    fmt.Println(strconv.Itoa(k))
  }
}

func main() {
  fmt.Println("test")
  go my()

  for {
    var p string
    fmt.Scanln(&p)
    fmt.Println("string from go: " + p)
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SilentFl, 2015-06-19
@LittleBuster

Your mistake is misunderstanding what a goroutine is. Goroutine != stream. Goroutines can be considered as some blocks of code that the runtime can execute in an arbitrary order (with the feeling that they are executed in parallel), and if the execution of the goroutine has begun, then it will not be interrupted (with a caveat - there is still switching between goroutines, on io- operations).
The solution is simple - you need to tell the runtime so that it does not execute the code in one thread (within the terms of the OS). For example like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question