Go language buffer channels: tips and Tricks

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Mahadevan Ramachandran January 15 channels and Goroutine are the core parts of the Go language based on the concurrency mechanism of the CSP (communicating sequential processes, communication sequence process). Read this article to learn some tips and tricks on channel, especially the "buffered" channel, which is widely used as a queue in the "producer-consumer" scenario. # # Buffer channel = Queue Buffer channel is a fixed capacity FIFO (FIFO) queue. Capacity is fixed when the queue is created-its size cannot be changed at run time. "' Goqueue: = Make (chan Item, Ten)//The capacity of the queue is up to a maximum of KiB, and the queue can store pointers and non-pointer elements. If you persist in using pointers, or if the elements themselves are pointer types, it is up to you to ensure that the objects that the elements used in the queue are pointing to are valid. "' Goqueue: = Make (chan *item, ten) Item1: = &item{foo:" Bar "}queue <-item1item1. Foo = "Baz"//valid, but this is not a good habit! The producer (the code that puts the element in the queue) can choose whether to block when the element is enqueued. The go//queue will be blocked when it is full, the queue <-item//in order to be able to put elements without blocking, the code is as follows: Var ok boolselect {case queue <-Item:ok = True Default:ok = false}//here, "OK" is://true = the element is not blocked to queue//False and the element is not enqueued, because the queue is full and blocked ' consumers usually take elements out of the queue and process them. If the queue is empty and the consumer has nothing to do, it will block until the producer puts an element. The go//takes out an element, or waits until it can remove the element item: = <-Queue "If you do not want the consumer to wait, the code is as follows:" ' Govar OK boolselect {case item = <-Queue:ok = True Default:ok = false}//here, "OK" is://true = Remove the element from the queue item (or the queue is closed, see below)//False = = no element is removed, the queue is empty and a blocking ' # # # closes the buffer channel buffer channel preferably by the producer close, The channel Shutdown event is sent to the consumer. If you need to close the channel outside of the producer or consumer, you must use external synchronization to ensure that the producer does not attempt to write to the closed channel (which raises a panic). "' Goclose (queue)//close queue Close (queue)//" Panic: Close a closed channel "' # # Read or write to the closed channel can you write to the closed channel? Of course not. "' Goqueue <-Item//" Panic: Write "" to the closed channel so can I read it from the closed channel? In fact, before you go down, guess the output of this code: "' Gopackage mainimport" FMT "Func Main () {queue: = make (chan int, ten) queue <-< -Close (queue) fmt. Println (<-queue) fmt. Println (<-queue) fmt. Println (<-queue)} "There are [links] (https://play.golang.org/p/ot87ro27tFk) running the above code. (Translator Note: The following is the result of the operation) ' 10200 ' ' surprised? If you're wrong, remember to look here first! The read behavior of the:-) on the closed channel is special:-If the element is not removed, then the read operation will proceed as usual. -If the queue is empty and has been closed, the read is not blocked. -the "0 value" of the element type in the channel is returned when read on a channel that is empty and has been closed. These can help you understand why the above program will print out this result. But how do you tell if the data you read is valid? After all, "0 value" may also be a valid value. The answer is below: "' goitem, valid: = <-queue//here," valid "value://True =" Item "Valid/false =" queue "has been closed," item "is just a" zero Value "" So you can write consumer code like this: "' gofor {item, VAlid: = <-queue if!valid {break}//Processing item}//here, all the elements that are put into the queue have been processed,//and the queue has been closed "in fact," for. Range "loop is a simpler way of writing:" ' gofor Item: = Range Queue {//processing item}//here, all the elements that are put into the queue have been processed,//and the queue has been closed "' Finally, we can put The non-blocking and checking element validity is combined together: "' Govar OK, valid Boolselect {case item, valid = <-Queue:ok = True Default:ok = false}//to here://O K && valid = Item valid, can use//!ok = Channel is not closed, but channel is empty, retry later/OK &&!valid = channel is closed, exit polling ' # # Consulting and training required Want to help get a project that uses Golang? We have extensive experience in creating and running production-level Go platform software solutions. We can help you architect and design a Go platform project, or provide advice and oversight for teams that use go. We also provide training or enhance Golang knowledge for teams wishing to carry out go projects. [Discover more HERE] (https://www.rapidloop.com/training) or [Contact us now] (https://www.rapidloop.com/contact) to discuss your needs! **mahadevan Ramachandran**co-founder & CEO, Rapidloop [@mdevanr] (HTTPS://TWITTER.COM/MDEVANR)

Via:https://www.rapidloop.com/blog/golang-channels-tips-tricks.html

Author: Aaron Schlesinger Translator: Sunzhaohao proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

739 Reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.