第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go 在睡眠時超時,但在忙等待時不會超時

Go 在睡眠時超時,但在忙等待時不會超時

Go
胡子哥哥 2021-07-29 13:01:19
在 Go 中,我可以使用time.After超時睡眠函數(shù),但我不能對忙等待(或工作)的函數(shù)執(zhí)行相同的操作。以下代碼timed out一秒后返回,然后掛起。package mainimport (        "fmt"        "time")func main() {        sleepChan := make(chan int)        go sleep(sleepChan)        select {        case sleepResult := <-sleepChan:                fmt.Println(sleepResult)        case <-time.After(time.Second):                fmt.Println("timed out")        }        busyChan := make(chan int)        go busyWait(busyChan)        select {        case busyResult := <-busyChan:                fmt.Println(busyResult)        case <-time.After(time.Second):                fmt.Println("timed out")        }}func sleep(c chan<- int) {        time.Sleep(10 * time.Second)        c <- 0}func busyWait(c chan<- int) {        for {        }        c <- 0}為什么在第二種情況下超時不觸發(fā),我需要使用什么替代方法來中斷工作的 goroutines?
查看完整描述

1 回答

?
HUH函數(shù)

TA貢獻1836條經(jīng)驗 獲得超4個贊

該for {}語句是一個無限循環(huán),它獨占一個處理器。設置runtime.GOMAXPROCS為 2 或更多以允許計時器運行。


例如,


package main


import (

    "fmt"

    "runtime"

    "time"

)


func main() {

    fmt.Println(runtime.GOMAXPROCS(0))

    runtime.GOMAXPROCS(runtime.NumCPU())

    fmt.Println(runtime.GOMAXPROCS(0))

    sleepChan := make(chan int)

    go sleep(sleepChan)

    select {

    case sleepResult := <-sleepChan:

        fmt.Println(sleepResult)

    case <-time.After(time.Second):

        fmt.Println("timed out")

    }


    busyChan := make(chan int)

    go busyWait(busyChan)

    select {

    case busyResult := <-busyChan:

        fmt.Println(busyResult)

    case <-time.After(time.Second):

        fmt.Println("timed out")

    }

}


func sleep(c chan<- int) {

    time.Sleep(10 * time.Second)

    c <- 0

}


func busyWait(c chan<- int) {

    for {

    }

    c <- 0

}

輸出(4 CPU 處理器):


1

4

timed out

timed out


查看完整回答
反對 回復 2021-08-02
  • 1 回答
  • 0 關注
  • 205 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號