[A "strange" feature of the Go language]channel

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

(go from Go technology morning reading)

The Go language channel has a seemingly odd feature, which is that if you write to or read data to a channel that is null (nil), the current goroutine will block forever.

The above four main functions will always block (but because there is no other goroutine, runtime will report a deadlock error)

Why did go team design this?

It is said to implement a pattern called "guarded selective wating", and conditional wait: In some cases in select, if the corresponding conditions are not met, wait on this case.

There is such a scenario:


With the nil channel feature, it can be implemented with great elegance:


These are permanent blocks that are implemented using nil channel.

——-——————————— Ornate split line ——————————————

If we create a channel, but do not write data to it is not closed, just read the data, can also achieve the effect of permanent blocking. The effect is as follows:

This means that the permanent blocking feature of the nil channel is not necessary for the implementation of the "guarded selective wating" mode, but the nil channel is obviously more convenient, There is no need to waste additional resources to create a channel to permanently block.




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.