2 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
代碼創(chuàng)建一個(gè)容量為 1的緩沖通道。當(dāng)通道已滿時(shí),自動(dòng)收?qǐng)?bào)機(jī)會(huì)丟棄時(shí)間值。
這是問(wèn)題中跟蹤的時(shí)間表。同一時(shí)間列出的事件按列出的順序依次發(fā)生一點(diǎn)點(diǎn)。
1s - ticker sends value
1s - main goroutine receives first value
1s - main goroutine starts sleep for 5s
2s - ticker sends value (channel has capacity 1).
3s - ticker fails to send value because channel is full
4s - ticker fails to send value because channel is full
5s - ticker fails to send value because channel is full
6s - main goroutine exits sleep and receives buffered value
6s - ticker sends value
6s - main goroutine receives buffered value
ticker 和 main goroutine 跑到 6s 標(biāo)記,因?yàn)?sleep 是 ticker 周期的倍數(shù)。在您的跟蹤中,主 goroutine 贏得了比賽。在我的機(jī)器上,自動(dòng)收?qǐng)?bào)機(jī)贏得了比賽,我得到了你期望的時(shí)間。這是我機(jī)器上的樣子。
...
5s - ticker fails to send value because channel is full
6s - ticker fails to send value because channel is full
6s - main goroutine receives buffered value
7s - ticker sends value
7s - main goroutine receives value
自動(dòng)收?qǐng)?bào)機(jī)在操場(chǎng)上以 6 秒的成績(jī)贏得比賽。 在這里運(yùn)行它。當(dāng)睡眠時(shí)間減少 1μs 時(shí),主 goroutine 贏得了比賽。在這里運(yùn)行它。
當(dāng)睡眠持續(xù)時(shí)間不是代碼周期的倍數(shù)時(shí),這很容易看出。以下是睡眠持續(xù)時(shí)間為 2.5 秒時(shí)發(fā)生的情況:
1s - ticker sends value
1s - main goroutine receives first value
1s - main goroutine starts sleep for 2.5s
2s - ticker sends value
3s - ticker fails to send value because channel is full
3.5s - main goroutine exits sleep and receives buffered value
4s - ticker sends value
4s - main goroutine receives value

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
在time.Ticker中,有一個(gè)chan Time
. 在NewTicker(d Duration) *Ticker
函數(shù)中,它創(chuàng)建tickers時(shí)間通道作為容量為1的緩沖通道。在函數(shù)中,如下所述。
// 給通道一個(gè) 1 元素的時(shí)間緩沖區(qū)。
// 如果客戶在閱讀時(shí)落后了,我們將滴答聲
// 放在地板上,直到客戶趕上。
在您的情況下,時(shí)間每秒都會(huì)滴答并寫入頻道。睡眠時(shí),ticker 向通道寫入一次,循環(huán)繼續(xù)后立即被 select case 接收并打印。在另外 4 秒內(nèi),通道被阻塞并且滴答聲被丟棄。立即循環(huán)繼續(xù)它被暢通并接受更多的通道滴答聲。
通過(guò)通道打印時(shí)間,您可以輕松了解行為。更新代碼如下。
func main() {
ticker := time.NewTicker(1 * time.Second)
i := 0
for {
select {
case t := <-ticker.C:
log.Println(i, t)
if i == 0 {
time.Sleep(5 * time.Second) // simulate the blocking
}
i++
}
}
}
輸出:
2022/02/20 08:47:58 0 2022-02-20 08:47:58.773375 +0530 +0530 m=+1.004241004
2022/02/20 08:48:03 1 2022-02-20 08:47:59.772787 +0530 +0530 m=+2.003666993
2022/02/20 08:48:03 2 2022-02-20 08:48:03.774272 +0530 +0530 m=+6.005207433 // printing time is same, but channel's received time has 4 sec difference.
2022/02/20 08:48:04 3 2022-02-20 08:48:04.774203 +0530 +0530 m=+7.005151715
- 2 回答
- 0 關(guān)注
- 245 瀏覽
添加回答
舉報(bào)