简体   繁体   中英

golang pass struct between two goroutines concurrently

I have two functions, What I would like to do is have a channel outside these two functions and have the first run in a go routine and update the channel and then the second function should read the items in the channel as they come in and do something else. When all the items in the channel are finished the go routines should exit gracefully

Could someone ELI5 how I can get two go routines reading from the same channel ? is that even possible ?

Something like the below...


package main

import (
    "fmt"
)

type Person struct {
    index int
    name  string
    age   int
}

func UpdatePeople(psn *chan Person, grNo int) {

    for i := 0; i < 5; i++ {
        psn := Person{
            index: 1,
            name:  "Shaun",
            age:   23,
        }
        fmt.Printf("Person: %v --- GoRoutineNumber: %v\n", psn, grNo)
    }

}

func WritePeople(psn *chan Person) {

    for i := 0; i < 5; i++ {
        psn := Person{
            index: 1,
            name:  "Shaun",
            age:   23,
        }
        fmt.Println("Writing People to DB", psn)
    }

}

func main() {

    //make channel of Person struct
    psnChan := make(chan Person)

    //I have a variable length in my program so lets say it's 6 in this case

    for i := 0; i < 6; i++ {

        /// I want to start a go routine here that writes to pointer of psnChan
        go UpdatePeople(&psnChan, i)

    }

    // I then want to read in from the channel as UpdatePeople is writing to it in a separate go routine
    for {

        _, received := <-psnChan
        if received == false {
            fmt.Println("Break out of 2nd loop")
            close(psnChan)
            break
        } else {

          go    WritePeople(&psnChan)

        }

    }
    fmt.Println("Finished")
}



https://play.golang.org/p/ExJf3lY0VV8

The above deadlocks but is the simplest way I can explain without pasting in a lot of code.

As Sergio pointed out, the Main goroutine is blocking because its waiting read from the psns channel, but nothing is writing to it. There's a good piece of advice when writing Go to only write synchronous functions, and another that the function responsible for creating a channel controls when it is closed. As such, I've restructured what you wrote a little with these in mind: https://play.golang.org/p/vicGN40pGVQ . This program will slowly find Person objects, send them over the channel, and write each Person as it goes. Let us know if your use-case differs :) Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM