Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang channel didnt get closed

i am quite new with go especially channel. i tried to close a channel but it didn’t get closed thus making method

fmt.Println("transaksi finaly done")

and

fmt.Println("order finaly done")

didn’t get called by the program, what did i do wrong to exact?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

full code


func (u *Usecase) GetOrderDetailByIDUsecase(ctx context.Context, orderId uint64) (*order.OrderPageDetailResponseDTO, error) {
    var wg sync.WaitGroup
    runtime.GOMAXPROCS(2)
    orderCh := make(chan *order.OrderResponseDTO)
    transaksiCh := make(chan *transaksi.TransaksiResponseDTO)
    errCh := make(chan error, 2)

    wg.Add(1)
    go func() {
        fmt.Println("order start")
        orderResp, err := u.orderController.GetOrderByID(ctx, orderId)
        fmt.Println("order done")
        errCh <- err
        orderCh <- orderResp
        fmt.Println("transaksi finaly done")
        wg.Done()
    }()

    wg.Add(1)
    go func() {
        fmt.Println("transaksi start")
        transaksiResp, err := u.transaksiController.GetTransaksiByID(ctx, int64(orderId))
        fmt.Println("transaksi done")
        errCh <- err
        transaksiCh <- transaksiResp
        fmt.Println("transaksi finaly done")
        wg.Done()
    }()

    go func() {
        wg.Wait()
        close(errCh)
        close(orderCh)
        close(transaksiCh)
    }()
    
    for err := range errCh {
        if err != nil {
            return nil, err
        }
    }

    var orderResp *order.OrderResponseDTO
    var transaksiResp *transaksi.TransaksiResponseDTO
    select {
    case orderResp = <-orderCh:
    case transaksiResp = <-transaksiCh:
    }

    return &order.OrderPageDetailResponseDTO{
        Order:     orderResp,
        Transaksi: transaksiResp,
    }, nil
}

>Solution :

Your "producer" goroutines are blocked on orderCh and transaksiCh. Since you didn’t give them a size in the call to make, the write will block until somebody is ready to read it. The same goroutine that reads those channels waits for errCh to close, but that depends on the producer goroutines both finishing because of your WaitGroup.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading