在我的机器上有 4 个逻辑处理器。所以有四个上下文P1, P2, P3&P4使用 OS 线程M1, M2, M3&M4
$ lscpu
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 4
On-line CPU(s) list: 0-3
Thread(s) per core: 2
Core(s) per socket: 2
Socket(s): 1
在下面的代码中:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func getPage(url string) (int, error) {
resp, err := http.Get(url)
if err != nil {
return 0, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, err
}
return len(body), nil
}
func worker(urlChan chan string, sizeChan chan<- string, i int) {
for {
url := <-urlChan
length, err := getPage(url)
if err == nil {
sizeChan <- fmt.Sprintf("%s has length %d (%d)", url, length, i)
} else {
sizeChan <- fmt.Sprintf("%s has error %s (%d)", url, err, i)
}
}
}
func main() {
urls := []string{"http://www.google.com/", "http://www.yahoo.com",
"http://www.bing.com", "http://bbc.co.uk", "http://www.ndtv.com", "https://www.cnn.com/"}
urlChan := make(chan string)
sizeChan := make(chan string)
for i := 0; i < len(urls); i++ {
go worker(urlChan, sizeChan, i)
}
for _, url := range urls {
urlChan <- url
}
for i := 0; i < len(urls); i++ {
fmt.Printf("%s\n", <-sizeChan)
}
}
有六个执行例程http.Get()
1)
OS thread() 是否被io() 上M1的 go-routine() 阻塞?上下文G1http.Get()P1
或者
G1Go 调度程序是否会从 OS 线程(M1)抢占 go-routine( ) http.Get()?并分配G2给M1... 如果是,则在抢占 时G1,G1Goruntime如何G1在 IO() 完成后恢复http.Get?
2)
检索用于每个 go-routine(G) 的上下文编号 (P) 的 api 是什么?用于调试目的..
3) 我们使用 C pthreads 库为上述读写器问题使用计数信号量维护关键部分。为什么我们不使用 go-routines 和通道来使用关键部分?
有只小跳蛙
相关分类