gpt4 book ai didi

Gogoutine调度算法

转载 作者:IT王子 更新时间:2023-10-29 02:24:15 24 4
gpt4 key购买 nike

package main

import ()

func main() {
msgQueue := make(chan int, 1000000)
netAddr := "127.0.0.1"
token := make(chan int, 10)
for i := 0; i < 10; i++ {
token <- i
}
go RecvReq(netAddr, msgQueue)
for {
select {
case req := <-msgQueue:
go HandleReq(req, token)
}
}
}

func RecvReq(addr string,msgQueue chan int){
msgQueue<-//get from network
}

func HandleReq(msg int, token chan int) {
//step 1
t := <-token
//step 2
//codo here...(don't call runtime.park)
//step 3
//code here...(may call runtime.park)
//step 4
token <- t
}

系统:1cpu 2core

Go版本:go1.3 linux/amd64

问题描述:

msgQueue revc 一直通过 RecvReq 请求,然后 main goroutine 一直在创建新的 goroutine,但是 waiting goroutine 一直在等待。前 10 个 goroutine 在第 3 步停止,新的 goroutine 在第 1 步停止。

Q1:一直在创建新的goroutine,如何让等待的goroutine运行。

Q2:如何平衡RevcReq和HandleReq? Revc msg 速率比 Handle msg 快 10 倍。

最佳答案

唉,从你的问题来看这不是很清楚。但是这里有几个问题。

  1. 您创建一个大小为 n 的缓冲 channel ,然后将 n 项插入其中。不要这样做——或者更清楚地说,在您知道需要这样做之前不要这样做。缓冲 channel 通常属于“过早优化”类别。从无缓冲 channel 开始,这样您就可以了解 goroutines 如何合作。当它工作时(没有死锁),测量性能,添加缓冲,再试一次。

  2. 您的select 只有一名 guard 。所以它的行为就像 select 不存在,而 case body 是那里唯一的代码。

  3. 您正在尝试为每条消息生成新的 goroutine。这真的是你想要的吗?您可能会发现您可以使用 goroutine 的静态网格,在您的情况下可能有 10 个,结果可能是一个意图更清晰的程序。它还会节省少量费用,因为运行时不必动态生成和清理 goroutine(但是,在担心任何低效问题之前,您应该首先关注正确的行为)。

  4. playground 示例中缺少您的 RecvReq,该示例不可执行。

关于Gogoutine调度算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26827733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com