问题描述
正如我们所知道的那样,当goroutine必须执行一个阻塞调用(例如系统调用)或通过cgo调用C库时,可能会创建一个线程。一些测试代码: 包主
$ b导入(
io / ioutil
os
runtime
strconv
)
func main(){
runtime.GOMAXPROCS(2)
data,err:= ioutil.ReadFile(./ 55555.log)
if err!= nil {
println(err)
return
}
代表i:= 0;我< 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 {}
}
当我运行它时,它不会创建很多线程。
➜= 99 = [root / root] $ cat / proc / 9616 / status | grep -i线程
线程:5
任何想法?
我稍微改变了你的程序,输出了一个更大的块
<$ (
io / ioutil
os
运行时
$ strconv
)
func main(){
runtime.GOMAXPROCS(2)
data:= make([] byte,128 * 1024 * 1024)
for i:= 0;我< 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)
}
选择{}
}
然后显示> 200个线程p>
$ cat / proc / 17033 / status | grep -i线程
线程:203
所以我认为系统调用退出太快您的原始测试,以显示您期待的效果。
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
Any ideas?
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 {}
}
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写入文件时,许多goroutines被阻塞时,它不会创建许多线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!