Golang channel使用示例

更新于 2022-10-29 10:28 56
专栏: Golang 标签: Go

介绍后期完善…

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. // main2()
  8. // main3() // 单向
  9. // main4() // 循环
  10. // main5() // select
  11. main6() // 利用阻塞实现同步操作
  12. }
  13. // 非缓冲通道buffer
  14. func main1() {
  15. ch := make(chan string)
  16. go func() {
  17. ch <- "str"
  18. }()
  19. fmt.Println(<-ch)
  20. }
  21. // 缓冲通道buffer
  22. func main2() {
  23. ch := make(chan string, 2)
  24. ch <- "str"
  25. fmt.Println(<-ch)
  26. }
  27. // receiver 只能做接收
  28. func receive(receiver chan<- string, str string) {
  29. receiver <- str
  30. }
  31. func send(sender <-chan string, receiver chan<- string) {
  32. str := <-sender
  33. receiver <- str
  34. }
  35. func main3() {
  36. ch1 := make(chan string, 1)
  37. ch2 := make(chan string, 1)
  38. receive(ch1, "hello")
  39. send(ch1, ch2)
  40. fmt.Println(<-ch2)
  41. }
  42. // 循环
  43. func main4() {
  44. ch := make(chan int, 10)
  45. for i := 0; i < 10; i++ {
  46. ch <- i
  47. }
  48. close(ch)
  49. res := 0
  50. for v := range ch {
  51. res += v
  52. }
  53. fmt.Println(res)
  54. }
  55. // select
  56. func strworker(ch chan string) {
  57. time.Sleep(1 * time.Second)
  58. fmt.Println("get into strworker. . .")
  59. ch <- "hello"
  60. }
  61. func intworker(ch chan int) {
  62. time.Sleep(1 * time.Second)
  63. fmt.Println("get into intworker. ..")
  64. ch <- 1
  65. }
  66. func main5() {
  67. chInt := make(chan int)
  68. chStr := make(chan string)
  69. go func() {
  70. strworker(chStr)
  71. }()
  72. go func() {
  73. intworker(chInt)
  74. }()
  75. for i := 0; i < 2; i++ {
  76. select {
  77. case <-chStr:
  78. fmt.Println("get value from chStr")
  79. case <-chInt:
  80. fmt.Println("get value from chInt")
  81. }
  82. }
  83. }
  84. // 阻塞实现同步
  85. func worker(ch chan string) {
  86. fmt.Println("get into worker...")
  87. ch <- "str"
  88. }
  89. func main6() {
  90. ch := make(chan string)
  91. go worker(ch)
  92. <-ch
  93. }