go language basic channel channel

1. The concept of channel:
Channel, channel, is specially used to pass messages between goroutines.
It is also a reference type of data: it can be used as a parameter or as a return value
Syntax:
1. Create: make(chan T)
2. Use:
Send data: write
chan <- data
Receive data: read
data := <- chan
Channel blocking:
without buffering: both sending and receiving are blocked.
Sending is blocking until another goroutine reads the data and unblocks it.
Similarly, receiving is also blocked until another goroutine writes data to unblock
2. Close the channel: The sender closes the channel to notify the receiver that there is no more data.
close(chan),
v, ok <-
After chan closes the channel, when other goroutines access the channel to obtain data, they get zero and false
A: infinite loop, there can be an end condition.
for{
v ,ok := <- chan
if ok== false{
//The channel has been closed. .
break
}
}
B: The for range chan
loop gets data from the channel until the channel is closed.
for v := range chan{
....v

}

package main

import "fmt"
 func main () {
    /*
    Channel, channel,
       1. For goroutine, for message delivery.
      2. Channels, each with an associated data type,
          nil chan, cannot be used, similar to nil map, cannot directly store key-value pairs
       3. Use channels to pass data: <-
          chan <- data, send data to the channel. Write data to the channel
          data <- chan, get data from the channel.       4. Blocking:
          sending data: chan <- data, blocked, until another goroutine, reading data to unblock
         reading data
 : data <- chan, also blocking. Unblock until another goroutine writes out data.
      5. The channel itself is synchronous, which means that only one goroutine can operate at the same time.
    */
 var ch1 chan bool //Declaration, not created
 fmt.Println(ch1) //<nil>
 fmt.Printf( "%T\n"
          , ch1) //chan bool
    ch1 = make ( chan bool ) //0xc042036060, is the data of reference type
    fmt.Println(ch1)


   go func() {
      for i:=0; i<10; i++ {
         fmt.Println("子goroutine中,i:",i)
      }
      // After the loop is over, write data to the channel, indicating that it is over. .
      ch1 <- true
 fmt.Println( "End.." )
      


   }()


   data:=<- ch1 // read data from ch1 channel
    fmt.Println( "data-->" , data)
   fmt.Println("main。。over。。。。")
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325893895&siteId=291194637