Question

I am writing a DNS protocol parser in golang, the idea is to use a map like this

var tidMap map[uint16] (chan []byte)

So for the tidMap map, key is the tid (transaction ID), value is a byte array channel.

The idea is that a goroutine will try get value from the channel, another goroutine will try read bytes by listening every imcoming packet, and once found transaction ID, will set response data to the tidMap, so the former goroutine will continue handle the response.

One problem with the design is that I need the make sure the channel has buffer length of 1, so extra values can be pushed into channel without blocking.

So how can I specify channel buffer length in tidMap declaration?

var tidMap map[int] make(chan int, 1)

You can't use make() there.

Was it helpful?

Solution

The length of the channel buffer doesn't convey type, so you will have to add logic to test if the map entry exists, if it doesn't:

tidMap[0] = make(chan int, 1)

OTHER TIPS

The short answer: you can't. When you make a map, you define the data types of its keys and values, and the capacity of a channel is not part of its type.

The longer answer is: create an abstract data type that hides this implementation detail. Something like this:

type ChannelMap struct {
    tidMap map[int](chan []byte)
}

func NewChannelMap() *ChannelMap { ... }

func (c *ChannelMap) Put(tid int) (chan int) { 
    res := make(chan int, 1)
    c.tidMap[tid] = res
    return res
}

func (c *ChannelMap) Get(tid int) (chan int) {
    return c.tidMap[tid]
}

And just to be sure: giving the channel a capacity of 1 does not ensure that senders will never block; if your channel consumers are too slow, producers can fill the channel up to its capacity and will then block until the channel has room again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top