Skip to content

example of using a channel for communication#16

Open
egonelbre wants to merge 1 commit into
jpaulm:masterfrom
egonelbre:channel
Open

example of using a channel for communication#16
egonelbre wants to merge 1 commit into
jpaulm:masterfrom
egonelbre:channel

Conversation

@egonelbre

@egonelbre egonelbre commented Sep 10, 2021

Copy link
Copy Markdown
Contributor

This PR demonstrates how channels (Go-s built-in concurrent queues) work.

Note, I'm aware you may not want to switch yet, so it's more of an educational PR, I guess.

In principle there are few things to know:

packets := make(chan *Packet, 100) // 100, says it's a buffered channel with capacity 100

// To send data over the packet:
packets <- pkt

// To receive data from the channel
pkt := <-packets

// To also detect why the receive returned:
pkt, ok := <-packets
// this `ok` is a boolean that tells whether there was any actual data received.
// If the channel is empty and closed then that will be `false`.

len(packets) // <-- how many items are currently in the queue
cap(packets) // <-- capacity of the queue

// To close the queue:
close(packets)

// One thing to keep in mind, once a channel is closed it cannot be reopened.
// If you want to reopen it, then you would need to re-create the queue.
// And calling `close` on a channel is allowed only once.

There are few other things that channels allow, for example receiving/sending from multiple queues at the same time.

As an example if we have two input ports and one output port we could implement a less than component that keeps sending the result of that comparison to output anytime one of the input values changes:

// this would be port initialization
leftPort := make(chan int)
rightPort := make(chan int)
outPort := make(chan bool)

// the component code
left := 0
right := 0
for {
	// wait for a value from either 
	select {
	case left = <-leftPort:
		fmt.Println("received value", left, "from left")
	case right = <-rightPort:
		fmt.Println("received value", right, "from right")
	}

	// send a value to output
	outPort <- left < right
}

Note, the code above currently does not handle closing of the incoming/outgoing connections.

@jpaulm jpaulm added the enhancement New feature or request label Sep 11, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants