Channels in Golang

Tram Ho

Hello guys, I continue with my series of days back to Golang. Today I will introduce you to Channels .

As mentioned earlier, Channels are a data structure that helps you communicate between goroutines. Channels help programmers avoid problems common in programming languages ​​that allow access to shared memory. One very difficult task of concurrency programming is to make sure your data is not suddenly changed by processes running concurrently (processes, thread or goroutines). When multiple threads (threads) access the same data (same device) at the same time without being locked or synchronized, uncontrolled data change occurs. In other languages, when you have global variables and share its memory. It is imperative that you use complex locking rules to avoid making asynchronous changes on the same variables. In Golang Channels provided a solution to help you handle this problem. Channels make sure only one and only one goroutine is allowed to change data at any given time.

Illustration

So where in your app will use channels to communicate between goroutines . Imagine, in an application there are many different processes that need to know or modify data in order. Using goroutines and channels , you can safely model the process. In the picture above, you see 3 goroutines and 2 unbuffered channels (this I will talk about in the next post). The first goroutine using the channel to transmit data to the second goroutine is ready. The process of transferring data between two goroutines is synchronizing, once the exchange occurs, both goroutines know the change has taken place. After the second goroutine does some task with the data, it sends that data to the waiting third goroutine. And of course the exchange is done synchronously, and both goroutines can ensure that the exchange is done. The exchange of data between goroutines is secure and does not require a lock or synchronization mechanism.

It’s very important to note that channels do not provide any way to protect data access between goroutines . If the copy of the data is exchanged via a channels, each goroutine will have a separate copy, and make changes any changes to such data safely. When the pointer is pointing to the data to be exchanged, each goroutine also needs to be synchronized if reads and writes are still performed at different goroutines .

I will end the article here. Any questions you just put in the comments, I will try to find out and answer your questions. Thank you for reading my article

Share the news now

Source : Viblo