Home>Article>Backend Development> How to determine whether channel is closed in golang

How to determine whether channel is closed in golang

尚
Original
2020-01-13 09:31:45 9042browse

How to determine whether channel is closed in golang

Map is an unordered collection of key-value pairs. The most important point of Map is to quickly retrieve data through key, which is similar to an index and points to the value of the data.

Map is a collection, so we can iterate over it just like arrays and slices. However, Map is unordered and we cannot determine the order in which it is returned. This is because Map is implemented using a hash table.

Let’s take a look at the method of determining whether a channel is closed in golang:

When reading a channel, determine whether it has been closed

_,ok := <- jobs

If the channel is closed at this time, the ok value is false

Judge whether it has been closed when writing to the channel

1._,ok := <- jobs

If the channel is closed at this time, the ok value is false. If the channel is not closed, one will be missed. jobs

2. Use the select method

to create another channel, called timeout. If it times out, send true to this channel, and the producer will send data to the job's channel. Use select to monitor the timeout, and if it times out, close the jobs channel.

go func() { time.Sleep(time.Second * 3) timeout <- true }()
go func() { for i := 0; ; i++ { select { case <-timeout: close(jobs) return default: jobs <- i fmt.Println("produce:", i) } } }()

For more golang knowledge, please pay attention to thegolang tutorialcolumn on the PHP Chinese website.

The above is the detailed content of How to determine whether channel is closed in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn