Search code examples
gosemaphorechannelgoroutine

Goroutine not executing after sending channel


package main

import (
    "fmt"
    "sync"
)

// PUT function
func put(hashMap map[string](chan int), key string, value int, wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Printf("this is getting printed")
    hashMap[key] <- value
    fmt.Printf("this is not getting printed")
    fmt.Printf("PUT sent %d\n", value)
}

func main() {
    var value int
    var key string
    wg := &sync.WaitGroup{}
    hashMap := make(map[string](chan int), 100)
    key = "xyz"
    value = 100
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go put(hashMap, key, value, wg)
    }
    wg.Wait()
}

The last two print statements in the put function are not getting printed, I am trying to put values into the map based on key.

and also how to close the hashMap in this case.


Solution

    1. You need to create a channel, for example hashMap[key] = make(chan int)
    2. Since you are not reading from the channel, you need buffered channel to make it work:
        key := "xyz"
        hashMap[key] = make(chan int, 5)
    

    Try the following code:

    func put(hashMap map[string](chan int), key string, value int, wg *sync.WaitGroup) {
        hashMap[key] <- value
        fmt.Printf("PUT sent %d\n", value)
        wg.Done()
    }
    func main() {
        var wg sync.WaitGroup
        hashMap := map[string]chan int{}
        key := "xyz"
        hashMap[key] = make(chan int, 5)
        for i := 0; i < 5; i++ {
            wg.Add(1)
            go put(hashMap, key, 100, &wg)
        }
        wg.Wait()
    }
    

    Output:

    PUT sent 100
    PUT sent 100
    PUT sent 100
    PUT sent 100
    PUT sent 100