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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

在使用通道的循環(huán)內(nèi)觸發(fā)通道

在使用通道的循環(huán)內(nèi)觸發(fā)通道

Go
躍然一笑 2022-11-23 16:06:48
如何在消耗相同通道的循環(huán)內(nèi)裝配通道。下面是一個(gè)不起作用的示例代碼。這是如何實(shí)現(xiàn)的?https://go.dev/play/p/o5ZhNfw4IFupackage mainimport (    "context"    "fmt"    "time")func main() {    ch1 := make(chan struct{})    ch2 := make(chan struct{})    defer close(ch1)    defer close(ch2)    ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)    defer cancel()    go func() {        time.Sleep(time.Second * 1)        ch1 <- struct{}{}    }()loop:    for {        select {        case <-ctx.Done():            fmt.Println("timeout")            break loop        case <-ch1:            fmt.Println("ch1")            ch2 <- struct{}{} // This here does not work!        case <-ch2:            fmt.Println("ch2")        }    }}去
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊

1.發(fā)送數(shù)據(jù)到goroutine里面的ch2

package main


import (

    "context"

    "fmt"

    "time"

)


func main() {

    ch1 := make(chan struct{})

    ch2 := make(chan struct{})

    defer close(ch1)

    defer close(ch2)


    ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)

    defer cancel()


    go func() {

        time.Sleep(time.Second * 1)

        ch1 <- struct{}{}

    }()


loop:

    for {

        select {

        case <-ctx.Done():

            fmt.Println("timeout")

            break loop

        case <-ch1:

            fmt.Println("ch1")

            go func() {

                ch2 <- struct{}{}

            }()

        case <-ch2:

            fmt.Println("ch2")

        }

    }


}


或者


2. 使 ch2 緩沖

package main


import (

    "context"

    "fmt"

    "time"

)


func main() {

    ch1 := make(chan struct{})

    ch2 := make(chan struct{}, 1)

    defer close(ch1)

    defer close(ch2)


    ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)

    defer cancel()


    go func() {

        time.Sleep(time.Second * 1)

        ch1 <- struct{}{}

    }()


loop:

    for {

        select {

        case <-ctx.Done():

            fmt.Println("timeout")

            break loop

        case <-ch1:

            fmt.Println("ch1")

            ch2 <- struct{}{}

        case <-ch2:

            fmt.Println("ch2")

        }

    }


}


查看完整回答
反對(duì) 回復(fù) 2022-11-23
  • 1 回答
  • 0 關(guān)注
  • 128 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)