Go routine 介紹

  • 要使用Go routine 只需要在函數前面加上 go 關鍵字即可。
  • 如果需要go routine 相互通信溝通,則需要使用 channel

正常範例

package main
import (
    "fmt"
)
func printHello() {
    fmt.Println("Hello World!")
}
func main() {
    fmt.Println("main execution started")
    // call function
    printHello()
    fmt.Println("main execution stopped")
}
In above program, we

加入 go routine

package main
import (
    "fmt"
)
func printHello() {
    fmt.Println("Hello World!")
}
func main() {
    fmt.Println("main execution started")
    // create goroutine
    go printHello()
    fmt.Println("main execution stopped")
}

// 結果
main execution started
main execution stopped
  • 少了 printHello() 的輸出,由於main goroutine 結束時,所以printHello goroutine執行時會看不到 printHello 的輸出。

加入延遲

package main
import (
    "fmt"
    "time"
)
func printHello() {
    fmt.Println("Hello World!")
}
func main() {
    fmt.Println("main execution started")
    // create goroutine
    go printHello()
    // schedule another goroutine
    time.Sleep(10 * time.Millisecond)
    fmt.Println("main execution stopped")
}

// 輸出
main execution started
Hello World!
main execution stopped

另一範例

package main
import (
    "fmt"
    "time"
)
func getChars(s string) {
    for _, c := range s {
        fmt.Printf("%c ", c)
    }
}
func getDigits(s []int) {
    for _, d := range s {
        fmt.Printf("%d ", d)
    }
}
func main() {
    fmt.Println("main execution started")
    // getChars goroutine
    go getChars("Hello")
    // getDigits goroutine
    go getDigits([]int{1,2,3,4,5})
    // schedule another goroutine
    time.Sleep(time.Millisecond)
    fmt.Println("\nmain execution stopped")
}

// 輸出
main execution started
H e l l o 1 2 3 4 5 
main execution stopped

匿名routine(Anonymous goroutines)

package main
import (
    "fmt"
    "time"
)
func main() {
    fmt.Println("main execution started")
    // create goroutine
    go func() {
        fmt.Println("Hello World!")
    }()
    // schedule another goroutine
    time.Sleep(10 * time.Millisecond)
    fmt.Println("main execution stopped")
}

// 輸出
main execution started
Hello World!
main execution stopped

參考函數