If I am using channels properly should I need to use mutexes?

You don’t need mutex if you use channels correctly. In some cases a solution with mutex might be simpler though. Just make sure the variable(s) holding the channel values are properly initialized before multiple goroutines try to access the channel variables. Once this is done, accessing the channels (e.g. sending values to or receiving values … Read more

What are channels used for?

chan is a channel in Golang. In simple word you can think it as a box in which you put a item at one end and then pick it from other end. Unbuffered Channels Buffered Channel This is the small code I have written for you to understand channels. Now change order of go routines … Read more

How to collect values from N goroutines executed in a specific order?

Goroutines run concurrently, independently, so without explicit synchronization you can’t predict execution and completion order. So as it is, you can’t pair returned numbers with the input numbers. You can either return more data (e.g. the input number and the output, wrapped in a struct for example), or pass pointers to the worker functions (launched … Read more

Terminating function execution if a context is cancelled

Function calls and goroutines cannot be terminated from the caller, the functions and goroutines have to support the cancellation, often via a context.Context value or a done channel. In either case, the functions are responsible to check / monitor the context, and if cancel is requested (when the Context’s done channel is closed), return early. … Read more

RabbitMQ and relationship between channel and connection

A Connection represents a real TCP connection to the message broker, whereas a Channel is a virtual connection (AMQP connection) inside it. This way you can use as many (virtual) connections as you want inside your application without overloading the broker with TCP connections. You can use one Channel for everything. However, if you have … Read more

Is it OK to leave a channel open?

It’s OK to leave a Go channel open forever and never close it. When the channel is no longer used, it will be garbage collected. Note that it is only necessary to close a channel if the receiver is looking for a close. Closing the channel is a control signal on the channel indicating that … Read more

Goroutine does not execute if time.Sleep included

When the main function ends, the program ends with it. It does not wait for other goroutines to finish. Quoting from the Go Language Specification: Program Execution: Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other … Read more