Golang 控制协程并发数量

并发过高导致程序崩溃 1func main() { 2 var wg sync.WaitGroup 3 for i := 0; i < math.MaxInt32; i++ { 4 wg.Add(1) 5 go func(i int) { 6 defer wg.Done() 7 fmt.Println(i) 8 time.Sleep(time.Second) 9 }(i) 10 } 11 wg.Wait() 12} 1goroutine 1489841 [running]: 2internal/poll.(*fdMutex).rwlock(0xc000130060, 0x0?) 3 /usr/local/go/src/internal/poll/fd_mutex.go:147 +0x11b 4internal/poll.(*FD).writeLock(...) 5 /usr/local/go/src/internal/poll/fd_mutex.go:239 6internal/poll.(*FD).Write(0xc000130060, {0xc0ca328a90, 0x8, 0x8}) 7 /usr/local/go/src/internal/poll/fd_unix.go:370 +0x72 8os.(*File).write(...) 9 /usr/local/go/src/os/file_posix.go:48 10os.(*File).Write(0xc00012e008, {0xc0ca328a90?, 0x8, 0xc0cd90b750?}) 11 /usr/local/go/src/os/file.go:175 +0x65 12fmt.Fprintln({0x4b7ff8, 0xc00012e008}, {0xc0cd90b790, 0x1, 0x1}) 13 /usr/local/go/src/fmt/print.go:305 +0x75 14fmt.Println(...) 15 /usr/local/go/src/fmt/print.go:314 16main.main.func1(0x0?) 17 /root/zhuangqf/Blank/cmd/main.go:16 +0x8f 18created by main.main 19 /root/zhuangqf/Blank/cmd/main.go:14 +0x3c 20panic: too many concurrent operations on a single file or socket (max 1048575) 1panic: too many concurrent operations on a single file or socket (max 1048575) 1 个 file/socket 的上并发操作个数超过了上限(1048575),简而言之,系统的资源被耗尽了。0xFFFFF = 1048575 ...

八月 7, 2023

Golang Channel 使用场景

1. future/promise 1.1 单向接收 Channel 作为函数返回 sumSquares函数调用的两个实参请求并发进行。每个通道读取操作将阻塞到请求返回结果为止。 1func longTimeRequest() <-chan int64 { 2 r := make(chan int64) 3 4 go func() { 5 time.Sleep(time.Second * 3) // 模拟一个工作负载 6 r <- rand.Int63n(100) 7 }() 8 9 return r 10} 11 12func sumSquares(a, b int64) int64 { 13 return a*a + b*b 14} 15 16func main() { 17 18 a, b := longTimeRequest(), longTimeRequest() 19 fmt.Println(sumSquares(<-a, <-b)) 20} 1.2 单向发送 Channel 作为函数实参 sumSquares函数调用的两个实参的请求也是并发进行的。和上例不同的是longTimeRequest函数接收一个单向发送通道类型参数而不是返回一个单向接收通道结果。 ...

八月 3, 2023