goroutine/Gosched/Goexit/GOMAXPROCS

來源:互聯網
上載者:User

標籤:退出   cpu   ack   垃圾   記憶體   package   並行計算   也會   回收機制   

goroutine
// code_037_concurrency_goroutine project main.gopackage mainimport (    "fmt"    "time")//並發,concurrency; 並行,parallel;而Go從語言層面就支援了並行,而Go語言提供了自動記憶體回收機制。//goroutine說到底其實就是協程,執行goroutine只需極少的棧記憶體(大概是4~5KB),當然會根據相應的資料伸縮func newTask() {    i := 0    for {        i++        fmt.Printf("new gorotine: i= %d\n", i)        time.Sleep(1 * time.Second)        if i == 10 {            break        }    }}func main() {    go newTask()    //goroutine>>> 主goroutine退出後,其它的工作goroutine也會自動結束    i := 0    for {        i++        fmt.Printf("main goroutine : i =%d\n", i)        time.Sleep(1 * time.Second)        if i == 10 {            break        }    }}
Goexit >>>
// code_039_goroutine_runtime_Goexit project main.gopackage mainimport (    "fmt"    "runtime")//備忘:調用 runtime.Goexit() 將立即終止當前 goroutine 執?,調度器確保所有登入 defer延遲調用被執行。func main() {    go func() {        defer fmt.Println("A.defer")        func() {            defer fmt.Println("B.defer")            runtime.Goexit() // 終止當前 goroutine, import "runtime"            fmt.Println("B") //不會執行        }()        fmt.Println("A") //不會執行    }()    //死迴圈,目的不讓主goroutine結束    for {    }}
Gosched >>>
// code_038_goroutine_runtime project main.gopackage mainimport (    "fmt"    "runtime")func main() {    //runtime包:Gosched()、Goexit()、GOMAXPROCS()    //runtime.Gosched() 用於讓出CPU時間片,讓出當前goroutine的執行許可權,調度器安排其他等待的任務運行,並在下次某個時候從該位置恢複執行。    //調用 runtime.Goexit() 將立即終止當前 goroutine 執行,調度器確保所有登入 defer延遲調用被執行。    //調用 runtime.GOMAXPROCS() 用來設定可以並行計算的CPU核心數的最大值,並返回之前的值。    go func(s string) {        for i := 0; i < 5; i++ {            fmt.Println(s)        }    }("world")    for i := 0; i < 5; i++ {        runtime.Gosched()        fmt.Println("Hello")    }}
GOMAXPROCS >>>
// code_040_goroutine_runtime_GOMAXPROCS project main.gopackage mainimport (    "fmt"    "runtime")//調用 runtime.GOMAXPROCS() 用來設定可以並行計算的CPU核心數的最大值,並返回之前的值。func main() {    n := runtime.GOMAXPROCS(1)    //  n := runtime.GOMAXPROCS(2)    fmt.Printf("n=%d\n", n)    for {        go fmt.Print(0)        fmt.Print(1)    }}

goroutine/Gosched/Goexit/GOMAXPROCS

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.