Go Goroutines

Da Andreabont's Wiki.

In GO è possibile lanciare funzioni in modo parallelo tramite le goroutines.

Esempio

Base

package main

import "fmt"

func counter(name string) {
    for i := 0; i < 3; i++ {
        fmt.Println(name, ":", i)
    }
}

func main () {
    
    go counter("1° goroutine")
    go counter("2° goroutine")
    
    var input string
    fmt.Scanln(&input)
    fmt.Println("done")
    
}

Channel

package main

import "fmt"

func wait(messages chan string) {
    
    for i := 0; i < 3; i++ {
        fmt.Println(">", i)
    }
    
    messages <- "END";
    
}

func main () {
    
    messages := make(chan string)
    
    go wait(messages)
    
    fmt.Println(<- messages)
    
}

Iteratore

package main

import "fmt"

func main () {
    
    messages := make(chan int)
    
    go func(x int) { 
        for i := 0; i < x; i++ {
            messages <- i
        }
        close(messages)
    }(3)
    
    for v := range messages {
        fmt.Println(">", v)
    }
    
}