首頁  >  文章  >  後端開發  >  使用通道將資料從一個 goroutine 傳遞到另一個 goroutine 時出現的問題

使用通道將資料從一個 goroutine 傳遞到另一個 goroutine 時出現的問題

PHPz
PHPz轉載
2024-02-08 23:21:08570瀏覽

使用通道将数据从一个 goroutine 传递到另一个 goroutine 时出现的问题

在Go語言的並發程式設計中,使用通道(channel)是一種常見的方式,用於在不同的goroutine之間傳遞資料。然而,在將資料從一個goroutine傳遞到另一個goroutine時,可能會出現一些問題。 php小編蘋果將在本文中介紹這些問題並提供解決方案,幫助您更好地理解和應對在並發編程中使用通道時可能遇到的困難。

問題內容

我已經能夠開發以下程式碼,該程式碼應該使用 go 通道將資料從一個例程傳遞到另一個例程:

package main

import (
    "fmt"
    "sync"
)

func generateNumbers(total int, wg *sync.WaitGroup) {
    defer wg.Done()
    ch :=make(chan int)

    sum :=0
    for idx := 1; idx <= total; idx++ {
        fmt.Printf("Generating number %d\n", idx)
        sum =sum+idx
        ch <- sum
    }
}

func printNumbers(wg *sync.WaitGroup, ch chan  int) {
    defer wg.Done()

    fmt.Printf("Sum is now",ch)
    for idx := 1; idx <= 3; idx++ {
        fmt.Printf("Printing number %d\n", idx)
    }
}

func main() {
    var wg sync.WaitGroup

    ch1 :=make(chan int)

    wg.Add(2)
    go printNumbers(&wg,ch1)
    go generateNumbers(3, &wg)

    fmt.Println("Waiting for goroutines to finish...")
    wg.Wait()
    fmt.Println("Done!")
}

我正在嘗試將資料( Sum 的值)從generateNumbers 傳遞到printNumbers 例程。

但我遇到以下問題:

Waiting for goroutines to finish...
Generating number 1
Sum is now%!(EXTRA chan int=0xc000102060)Printing number 1
Printing number 2
Printing number 3
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [semacquire]:
sync.runtime_Semacquire(0xc000118270?)
    /usr/local/go/src/runtime/sema.go:62 +0x27
sync.(*WaitGroup).Wait(0x4ba3a8?)
    /usr/local/go/src/sync/waitgroup.go:116 +0x4b
main.main()
    /tmp/tgPhZuPV77.go:42 +0x12f

goroutine 19 [chan send]:
main.generateNumbers(0x3, 0x0?)
    /tmp/tgPhZuPV77.go:19 +0xf2
created by main.main
    /tmp/tgPhZuPV77.go:39 +0xe5
exit status 2

請幫忙,我是 Golang 新手。

解決方法

上述程式存在一些錯誤。

  1. 這兩個函數 printNumbers 和generateNumbers 必須使用相同的 chan 變數。
  2. 您應該從 ch 讀取 chan 變數的資料。
  3. 此函數generateNumbers 不應重複宣告並建立chan 變數。

我將上面的程式碼修改如下:

func generateNumbers(total int, wg *sync.WaitGroup, ch chan int) {
    defer wg.Done()

    sum := 0
    for idx := 1; idx <= total; idx++ {
        fmt.Printf("Generating number %d\n", idx)
        sum = sum + idx
        ch <- sum
    }
}

func printNumbers(wg *sync.WaitGroup, ch chan int) {
    defer wg.Done()

    fmt.Printf("Sum is now:\n")
    for idx := 1; idx <= 3; idx++ {
        sum := <-ch
        fmt.Printf("Printing number %d %d\n", idx, sum)
    }
}

func main() {
    var wg sync.WaitGroup

    ch1 := make(chan int)

    wg.Add(2)
    go printNumbers(&wg, ch1)
    go generateNumbers(3, &wg, ch1)

    fmt.Println("Waiting for goroutines to finish...")
    wg.Wait()
    fmt.Println("Done!")
}

以上是使用通道將資料從一個 goroutine 傳遞到另一個 goroutine 時出現的問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除