本文介绍了golang写文件时阻塞了很多goroutine,为什么不创建很多线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如我们在 go 中所知,当 goroutine 必须执行阻塞调用时,可能会创建一个线程,例如系统调用,或通过 cgo 调用 C 库.一些测试代码:
As we know in go, a thread may be created when the goroutine has to perform a blocking call, such as a system call, or a call to a C library via cgo. Some test code:
package main
import (
"io/ioutil"
"os"
"runtime"
"strconv"
)
func main() {
runtime.GOMAXPROCS(2)
data, err := ioutil.ReadFile("./55555.log")
if err != nil {
println(err)
return
}
for i := 0; i < 200; i++ {
go func(n int) {
for {
err := ioutil.WriteFile("testxxx"+strconv.Itoa(n), []byte(data), os.ModePerm)
if err != nil {
println(err)
break
}
}
}(i)
}
select {}
}
当我运行它时,它没有创建很多线程.
When I run it, it didn't create many threads.
➜ =99=[root /root]$ cat /proc/9616/status | grep -i thread
Threads: 5
有什么想法吗?
推荐答案
我稍微修改了你的程序以输出更大的块
I altered your program slightly to output a much bigger block
package main
import (
"io/ioutil"
"os"
"runtime"
"strconv"
)
func main() {
runtime.GOMAXPROCS(2)
data := make([]byte, 128*1024*1024)
for i := 0; i < 200; i++ {
go func(n int) {
for {
err := ioutil.WriteFile("testxxx"+strconv.Itoa(n), []byte(data), os.ModePerm)
if err != nil {
println(err)
break
}
}
}(i)
}
select {}
}
这会如您所愿地显示 >200 个线程
This then shows >200 threads as you expected
$ cat /proc/17033/status | grep -i thread
Threads: 203
所以我认为系统调用在您的原始测试中退出得太快,无法显示您期望的效果.
So I think the syscalls were exiting too quickly in your original test to show the effect you were expecting.
这篇关于golang写文件时阻塞了很多goroutine,为什么不创建很多线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!