无缓冲的channel是同步的,而有缓冲的channel是非同步的
无缓冲channel在没有接收方的时候,发送方会阻塞
有缓冲channel在没有接收方的时候,如果缓冲区未满,则发送方并不会阻塞
type keyAndValue struct {
Key string
Value interface{}
}
func DealNids(ctx context.Context, ids []string) (string, error) {
if len(ids) == 0 {
return "",nil
}
waitGroup, channel := sync.WaitGroup{}, make(chan keyAndValue, len(ids))
for _, id := range ids {
waitGroup.Add(1)
go func(ctx context.Context, channel chan keyAndValue, waitGroup *sync.WaitGroup, id string) {
defer waitGroup.Done()
newId := id + "123"
data := keyAndValue{
Key: newId,
Value: newId,
}
channel <- data
}(ctx, channel, &waitGroup, id)
}
waitGroup.Wait()
close(channel)
result := make(map[string]interface{}, 0)
redisRes := ""
for value := range channel {
result[value.Key] = value.Value
}
return redisRes, nil
}