当前位置:网站首页>Select in golang concurrent programming

Select in golang concurrent programming

2022-06-22 03:23:00 ManNiaoQinFen

1.select yes Go A control structure in , Be similar to switch sentence , Used to handle asynchronous IO operation .select Will listen case In the sentence channel Read and write operations , When case in channel Read and write operations are non blocking ( Can read and write ) when , Will trigger the corresponding action .

select Medium case The statement must be a channel operation

select Medium default Clause is always runnable .

2. If there are more than one case Can run ,select One of them will be selected randomly and fairly , Others will not be executed .

3. If there is no running case sentence , And there are default sentence , Then it will carry out default The action of .

4. If there is no running case sentence , And there's no default sentence ,select Will block , Until some case Communication is operational

package main

import (
	"fmt"
	"time"
)

var chanInt = make(chan int)

var chanStr = make(chan string)

func main() {
    
	go func() {
    
		chanInt <- 10
		chanStr <- "hello"
		close(chanInt)
		close(chanStr)
	}()

	for {
    
		select {
    
		case r := <-chanInt:
			fmt.Printf("chanInt: %v\n", r)
		case r := <-chanStr:
			fmt.Printf("chanStr: %v\n", r)
		default:
			fmt.Println("default....")
		}
		time.Sleep(time.Second)
	}

}

Running results

chanInt: 10
chanStr: hello
chanStr: 
chanStr: 
chanStr: 
原网站

版权声明
本文为[ManNiaoQinFen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220308321947.html