go并发模式之----使用时顺序模式

常见模式之二:使用时顺序模式

定义

顾名思义,起初goroutine不管是怎么个先后顺序,等到要使用的时候,需要按照一定的顺序来,也被称为未来使用模式

使用场景

  • 每个goroutine函数都比较独立,不可通过参数循环复用

  • 任务各自独立,结果组合依赖顺序

示例

Go 复制代码
package main

import (
	"fmt"
	"time"
)

func grepMySQL() <-chan string {
	res := make(chan string)
	go func() {
		time.Sleep(time.Millisecond * 30)
		res <- "grep data from MySQL"
	}()
	return res
}

func grepSQLServer() <-chan string {
	res := make(chan string)
	go func() {
		time.Sleep(time.Millisecond * 10)
		res <- "grep data from SQLServer"
	}()
	return res
}

func grepRedis() <-chan string {
	res := make(chan string)
	go func() {
		time.Sleep(time.Millisecond * 20)
		res <- "grep data from Redis"
	}()
	return res
}

func main() {
	mysqlRes := grepMySQL()
	sqlServerRes := grepSQLServer()
	redisRes := grepRedis()

	// 数据排序规则是 redis -- mysql -- sqlServer
	resArr := []string{
		<-redisRes,
		<-mysqlRes,
		<-sqlServerRes,
	}
	fmt.Println(resArr)
}
相关推荐
fliter7 小时前
Go设计取舍之一: goroutine 为什么保持匿名、无状态
后端
fliter7 小时前
Go设计取舍之二: maps.Keys和Values为什么返回迭代器
后端
热心市民lcj7 小时前
Spring Boot 整合 Caffeine 本地缓存实战
spring boot·后端·缓存
Revolution618 小时前
Nest.js 是什么:怎样用它写出第一个后端接口
后端·node.js·nestjs
Richard.Wong8 小时前
qt生成dll供C#调用
开发语言·qt
aiopencode8 小时前
SwiftUI Introspect生产环境完全指南:为什么它是安全可靠的选择
后端·ios
wang_xin_8888 小时前
PHP函数
开发语言·php
shengjk18 小时前
x86架构发展史:从8086到x86-64,一文看懂40多年CPU指令集如何改变世界
后端
Immortal__y8 小时前
php函数
开发语言·php
AI砖家8 小时前
多商户多租户系统架构设计文档(Java版)
java·开发语言·系统架构·多租户·多商户