如何使Goroutine通过渠道相互交流

时间:2019-12-12 08:55:39

标签: go goroutine

我是Golang的新手,我正在尝试使用goroutine,以便他们可以在其中进行交谈。我有一些代码启动一个具有operation1的goroutine,我称它为跳舞。完成后,它会向另一个goroutine发送信号,该goroutine将执行其他操作2,例如,睡眠。

您可以将强制跳舞参数传递给goroutine,但是如果它已经处于跳舞状态,它将进入睡眠状态。

package main

import (
    "fmt"
    "time"
)

func main(){
    test("notdancing", true)
    time.Sleep(10*time.Second)
}
func dance()error{
    fmt.Println("Tapping my feet")
    time.Sleep(10*time.Second)
    return nil
}
func test(status string, forceDance bool) {

时不起作用
   //startSleep := make(chan bool)

为什么需要为通道提供缓冲区长度才能使其正常工作?我尝试了没有缓冲区长度的尝试,但是它说如果我不将1作为第二个参数传递,那么所有goroutine都在睡眠。

    startdance := make(chan bool, 1)
    startSleep := make(chan bool, 1)

    if status == "dancing" && forceDance {
        select {
        case startSleep <-true:
            fmt.Println("Would start to sleep now")
        default:
            fmt.Println("Sleep Already started. No need to force")
        }
    }

    if status != "dancing" {
        fmt.Println("Startingdance")
        startdance <- true
    }

    go func() {
        <-startdance
        err := dance()
        if err == nil {
            select {
            case startSleep <- true:
                fmt.Println("Starting Sleeping, dancing completed")
            default:
                fmt.Println("Already started Sleeping")
            }
        } else {
            fmt.Println("Not in a mood to dance today")
        }
    }()

    go func() {
        <-startSleep
        if forceDance {
            fmt.Println("Force sleep because forcing to dance while already dancing")
        }
    }()

}

我非常感谢对代码的任何更正以及使用此方法的陷阱。

1 个答案:

答案 0 :(得分:3)

在无缓冲通道(未指定大小)的情况下,由于没有大小,因此无法保存值。因此,在通过通道写入/传输数据时,必须有读者在场,否则它将阻塞呼叫。

func main() {
    startDance := make(chan bool)
    startDance <- true
}

但是,当您在上面的代码中指定一个大小(例如1)时,它就不会死锁,因为它将有空间容纳数据。 (({https://robertbasic.com/blog/buffered-vs-unbuffered-channels-in-golang/)。)(https://www.golang-book.com/books/intro/10),您可以查看上述网站,以更好地了解渠道和并发性

package main

import (
    "fmt"
    "time"
)

func main() {
    startDance := make(chan bool)
    startSleep := make(chan bool)
    forceSleep := make(chan bool)
    go startDance1(startDance, forceSleep, startSleep)
    go performSleep(startSleep, startDance)
    startDance <- true
    fmt.Println("now dance is started ")
    forceSleep <- true
    select {}
}

func startDance1(startDance chan bool, forceSleep chan bool, startSleep chan bool) {

    fmt.Println("waiting to start dance")
    select {
    case <-startDance:
        fmt.Println("staring dance")
    }

    for {
        select {
        case <-startDance:
            fmt.Println("starting dance")
        case <-forceSleep:
            fmt.Println("aleardy dancing going to sleep")
            select {
            case startSleep <- true:

            default:
            }
        default:
            //this is just to show working this
            // i added default or else this will go into deadlock
            fmt.Println("dancing")
            time.Sleep(time.Second * 1)
        }
    }
}

func performSleep(startSleep chan bool, startDance chan bool) {
    select {
    case <-startSleep:
        fmt.Println("staring sleep")
    }
    fmt.Println("sleeping for 5 seconds ")
    time.Sleep(time.Second * 5)
    select {
    case startDance <- true:
        fmt.Println("started dance")
    default:
        fmt.Println("failed to start dance ")
    }
}

以上代码是对您的代码的一个小改进(我尝试根据您的要求进行修改)。建议您阅读一些书籍,以了解有关并发性的更多信息(https://www.golang-book.com/books/intro/10_