go没有buffer的channel的调用顺序

 

第一种情况 第二种情况 第三种情况 第四种情况
rb rb sb sb
sb sb rb rb
se re re se
re se se re

显然: send begin 早于 send end, 

   recv begin 早于 recv end,

------------------------------------------------

  可得: 非buffer 的channel时: send begin 早于 recv end ---------这条也好理解。(没有buffer, 【接收完成】 肯定要晚于 【发送开始】)

                recv begin 早于 send end ----------这条稍微难理解一点,比较重要。(因为有buffer时, 【recv begin】 可能晚于 【send end】)

 

 

 

 

https://segmentfault.com/a/1190000008230146

https://www.jianshu.com/p/5e44168f47a3

 

------------------------------------------------------------------------------------------

第一种: r, s, s, r

go没有buffer的channel的调用顺序

 

 

package main

import (
//  "log"
  "time"
)

var a string
var c = make(chan int)
func main() {
  go func() { 
    a = "hello\n"
    print("recv begin..\n")
    <-c
    sum :=0
    for i := 0; i<1<<24; i++ {
      sum += i
    }
    print("recv end..\n")
  }()
  sum :=0
  for i := 0; i<1<<24; i++ {
    sum += i
  }
  print("send begin..\n")
  c <-12
  print("send end..\n")
  print(a)
  time.Sleep(time.Second*2)
}

----------------------------------------

  第二种情况 r, s, r, s

go没有buffer的channel的调用顺序

 

 

 package main
 
 import (
 //  "log"
   "time"
 )
 
 var a string
 var c = make(chan int)
 func main() {
   go func() { 
     a = "hello\n"
     print("recv begin..\n")
     <-c
     
     print("recv end..\n")
   }()
   sum :=0
   for i := 0; i<1<<24; i++ {
     sum += i
   }
   print("send begin..\n")
   c <-12
   sum =0
   for i := 0; i<1<<24; i++ {
     sum += i
   }
   print("send end..\n")
   print(a)
   time.Sleep(time.Second*2)
 }

---------------------------------------

  第三种情况:s, r, r, s

go没有buffer的channel的调用顺序

 

 

package main

import (
//  "log"
  "time"
)

var a string
var c = make(chan int)
func main() {
  go func() { 
    a = "hello\n"
    print("recv begin..\n")
    <-c
    
    print("recv end..\n")
  }()
  print("send begin..\n")
  c <-12
  sum :=0
  for i := 0; i<1<<24; i++ {
    sum += i
  } 
  print("send end..\n")
  print(a) 
  time.Sleep(time.Second*2)
} 
  

-----------------------------------------  

第四种情况: s, r, s, r

go没有buffer的channel的调用顺序

 

 

package main

import (
//  "log"
  "time"
)

var a string
var c = make(chan int)
func main() {
  go func() { 
    a = "hello\n"
    print("recv begin..\n")
    <-c
    sum :=0
    for i := 0; i<1<<24; i++ {
      sum += i
    }

    print("recv end..\n")
  }()
  print("send begin..\n")
  c <-12
    print("send end..\n")
  print(a)
  time.Sleep(time.Second*2)
}

  

上一篇:IO模型


下一篇:网络编程之TCP多人聊天