[golang basics] golang development ideas (future mode)

前言:
		最近在学习golang,golang并发支持比较好,goroutine+channel这个思想,大大提高了并行效率。既然golang有这个特性,我在做一些多个子调用的时候完全可以使用channel来将串行调用更改为异步调用,大大提高运行效率。所以今天就来学习一下future模式。

1. What is future mode

When we are programming, we often call multiple sub-calls in a function. These sub-calls do not depend on each other. If they are called serially, it will take a long time. At this time, you can use future mode to develop .
Fundamental:

  • Use chan as a function parameter
  • Start goroutine call function
  • Pass in parameters via chan
  • Do other things that can be processed in parallel
  • Get results asynchronously through chan

2. Futrue benefits?

The biggest advantage of future is to convert the synchronous call of the function to an asynchronous call, which is suitable for the scenario where a transaction requires multiple sub-calls and these sub-calls have no dependencies.
The work flow chart is as follows:

Insert picture description here

3. Sample

Here, the operation of querying the database is simulated, and the futurem mode is used for development

package main

import (
	"fmt"
	"time"
)

//future 模式
/**
* 1. 使用chan作为函数参数
* 2. 启动goroutine调用函数
* 3. 通过chan传入参数
* 4. 做其他可以并行处理的事情
* 5. 通过chan异步获取结果
*/
 type query struct {
 	//参数channel
 	sql chan string
 	//结果channel
 	result chan string
 }

 //执行Query
func execQuery(q query)  {
	//启动一个goroutine
	go func() {
		sql := <-q.sql
		//访问数据库函数 这里省略

		//查询结束后 输出结果通道
		q.result <- "result form " + sql
	}()
}

func main()  {
	//初始化query
	q := query{
		sql:    make(chan string,1),
		result: make(chan string,1),
	}
	// 开启一个goroutine 执行 sql查询
	go execQuery(q)
	//发送参数
	q.sql <- "select * from table"
	time.Sleep(1*time.Second)
	fmt.Println(<-q.result)
}
Published 197 original articles · praised 73 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_39397165/article/details/105447017