Home  >  Article  >  Backend Development  >  How does golang determine that the channel has been closed?

How does golang determine that the channel has been closed?

尚
Original
2019-12-31 09:45:452970browse

How does golang determine that the channel has been closed?

Channel is somewhat similar to a pipeline. It plays a role in goroutine synchronization and communication. It is also the key to Golang's CSP model.

Most types in golang are value types (only slice/channel/map are reference types). When the read/write type is a channel of value type, if the element size is relatively large, pointers should be used instead. Avoid frequent memory copy overhead.

Golang's method to determine whether the channel has been closed:

Judge whether the channel has been closed when reading the channel

_,ok := <- jobs

If the channel is closed at this time Close, 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 job will be missed.

2. Use the select method

to create another channel, called timeout. If it times out, Send true to this channel, send data to the channel of jobs in the producer, use select to monitor the timeout, if it times out, close the channel of jobs.

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 togolang tutorial Column.

The above is the detailed content of How does golang determine that the channel has been closed?. 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