Golang協程實現流量統計系統(3)

進程、線程、協程

- 進程:太重

- 線程:上下文切換開銷太大

- 協程:輕量級的線程,簡潔的併發模式

 

Golang協程:goroutine

 

Hello world

package main

import "fmt"

func main() {
    fmt.Println("Hello world!")
}

 

  

Golang協程特性實踐

- go發起一個協程

- channel協程間通信,通道

- buffered channels具備緩衝隊列的通道

 

go協程和channel初次使用

package main

import (
"fmt"
)

func main() {
    message := make(chan string)//定義一個string型的channel
    go func() {
        message <- "hello goroutine!"
    }()
    
    fmt.Println( <- message )
    fmt.Println("Hello world!")
}

 

多個協程

package main

import (
    "fmt"
    "time"
)

func main() {
    message := make(chan string) //定義一個string型的channel
    go func() {
        message <- "hello goroutine!"
    }()
    go func() {
        time.Sleep(2 * time.Second)
        str := <-message
        str = str + "I'm goroutine!"
        message <- str
    }()
    time.Sleep(3 * time.Second)
    fmt.Println(<-message)
    fmt.Println("Hello world!")
}

 

  

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章