Go 語言併發編程保姆級教程!

哈嘍,大家好,我是 Go 大叔,專注分享 Go 語言知識,一起進入 Go 的大門。

大叔和身邊一羣大牛都無限看好 Go 語言,現在開始搞 Go 語言,過兩年大概就是第一批喫螃蟹的人。

併發編程基本概念

什麼是串行?

什麼是並行?

什麼是併發?

什麼是程序?

什麼是進程?

什麼是線程?

什麼是協程?

Go 併發

package main

import (
 "fmt"
 "time"
)

func sing()  {
 for i:=0; i< 10; i++{
  fmt.Println("我在唱歌")
  time.Sleep(time.Millisecond)
 }
}
func dance() {
 for i:=0; i< 10; i++{
  fmt.Println("我在跳舞---")
  time.Sleep(time.Millisecond)
 }
}

func main() {
 // 串行: 必須先唱完歌才能跳舞
 //sing()
 //dance()

 // 並行: 可以邊唱歌, 邊跳舞
 // 注意點: 主線程不能死, 否則程序就退出了
 go sing() // 開啓一個協程
 go dance() // 開啓一個協程
 for{
  ;
 }
}
 package main
 import (
  "fmt"
  "runtime"
 )
 
 func sing()  {
  for i:=0; i< 10; i++{
   fmt.Println("我在唱歌")
   // Gosched使當前go程放棄處理器,以讓其它go程運行。
   // 它不會掛起當前go程,因此當前go程未來會恢復執行
   runtime.Gosched()
  }
 }
 func dance() {
  for i:=0; i< 10; i++{
   fmt.Println("我在跳舞---")
   runtime.Gosched()
  }
 }
 
 func main() {
 
  go sing()
  go dance()
  for{
   ;
  }
 }
 package main
 import (
  "fmt"
  "runtime"
 )
 
 func main() {
  go func() {
   fmt.Println("123")
   // 退出當前協程
   //runtime.Goexit()
   // 退出當前函數
   //return
   test()
   fmt.Println("456")
  }()
  for{
   ;
  }
 }
 
 func test()  {
  fmt.Println("abc")
  // 只會結束當前函數, 協程中的其它代碼會繼續執行
  //return
  // 會結束整個協程, Goexit之後整個協程中的其它代碼不會執行
  runtime.Goexit()
  fmt.Println("def")
 }
 package main
 import (
  "fmt"
  "runtime"
 )
 func main() {
  num := runtime.NumCPU()
  fmt.Println(num)
 }
 func main() {
   // 獲取帶來了CPU個數
  num := runtime.NumCPU()
  // 設置同時使用CPU個數
  runtime.GOMAXPROCS(num)
 }

聲明:本文爲原創

一個人走的太慢,一羣人才能走的更遠。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/47a26-HLSKxMM0hjl7SSAg