Go语言的并发简单总结

Goexit结束当前goroutine,会调用defer, 不会产生panic
1.6.扇入扇出 fan in\fan out

1.7 通知退出机制
通知退出机制是学习使用context库的基础

Lable:
for{
	select {
	case ch<-rand.Int():
	case <-done:
		break Lable
	}
}

2.并发范式
2.1 生成器
2.2 管道
输入输出都是chan的时候,链式调用
2.3 每个请求一个goroutine
使用waitgroup同步处理过程,结束后统一处理结果,结果处理完使用close通道告诉后面range通道结束获取到完整结果。

工作通道读出来就go走,读到多少个数据就创建多少个协程,容易爆炸。
可以控制最大数量,弄一个有缓冲的channel,新建一个协程写入一个,表示占空,处理完再读出来,表示用完了挪开。问题是协程会一直创建销毁。
2.4 固定worker工作池
分出n个协程来一起读通道,读到就操作,操作完了再读。工作池是固定的,没有数据时就会有n个占用的通道等待读取。

2.5 future模式
一个流程需要多个子调用,且这些子调用相互没有依赖。
新建一个协程用来读取任务、处理任务并返回任务,主线只需要把任务放进去,在需要的时候读取出来,不影响总进度。也是占坑方式。

3.context
设计目的:
1.退出通知机制 主要目的
2.传递数据 额外功能,因为传递的都是interface{},编译器不能进行严格的类型校验。
应该传递的消息:
日志信息、调试信息、不影响业务的可选数据。

<div class="post-text" itemprop="text"> <p>I am currently working on a web service in Go that essentially takes a request and sends back JSON, rather typical. However, this particular JSON takes 10+ seconds to actually complete and return. Because I am also making a website that depends on the JSON, and the JSON contents are subject to change, I implemented a route that quickly generates and returns (potentially updated or new) names as placeholders that would get replaced later by real values that correspond to the names. The whole idea behind that is the website would connect to the service, get back JSON almost immediately to populate a table, then wait until the actual data to fill in came back from the service.</p> <p>This is where I encounter an issue, potentially because I am newish to Go and don't understand its vast libraries completely. The previous method that I used to send JSON back through the HTTP requests was ResponseWriter.Write(theJSON). However, Write() terminates the response, so the website would have to continually ping the service which could now and will be disastrous in the future</p> <p>So, I am seeking some industry knowledge into my issue. Can HTTP connections be continuous like that, where data is sent piecewise through the same http request? Is that even a computationally or security smart feature, or are there better ways to do what I am proposing? Finally, does Go even support a feature like that, and how would I asynchronously handle it for performance optimization?</p> <p>For the record, my website is using React.js. Thanks!</p> </div>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付 9.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值