Go routine協程

         Go 語言在語言級別支持輕量級線程,叫goroutine。Go 語言標準庫提供的全部系統調用操做
(固然也包括全部同步 IO 操做),都會出讓 CPU 給其餘goroutine。這讓事情變得很是簡單,讓輕

量級線程的切換管理不依賴於系統的線程和進程,也不依賴於CPU的核心數量。好像沒有說道有線程的概念 shell

代碼以下: 數組

goroutine/
├── bin
│   └── goroutine
└── src
    └── goroutine.go
goroutine/src/goroutine.go
package main

import (
	"fmt"
	"time"
)

const (
	count = 10
)
/**
這是一個使用協程的例子
*/
func main(){
	//建立10個channel的數組
	chs := make([]chan int, count)

	//啓動10個協程(for range語句是循環容器go語法)
	for i, _ := range(chs){
		//i:數組下標, _是值, "_"佔位符表明值不處理, 若是要處理使用其餘變量名
		//初始化數組裏面的chan(chan是協程之間消息通道)
		chs[i] = make(chan int)
		fmt.Printf("go (%d, %s)\n", i, chs[i])
		//啓動協程(線程),go是啓動協程的關鍵字
		go do(i, chs[i])
	}

	//主線程便利獲取chan
	for i, ch := range(chs){
		//從chan中獲取內容,放入v
		v := <-ch
		//休眠1s
		time.Sleep(time.Second)
		//打印v
		fmt.Printf("chan[%d]->%d\n", i, v)
	}
}

//協程函數
func do(i int, ch chan int){
	fmt.Printf("%d->chan[%d]\n",i , i)
	//將i索引,寫入通道(<-)
	ch <- i
}
相關文章
相關標籤/搜索