进程、线程、协程

- 进程:太重

- 线程:上下文切换开销太大

- 协程:轻量级的线程,简洁的并发模式

 

Golang协程:goroutine

 

Hello world

package main

import "fmt"

func main() {
    fmt.Println("Hello world!")
}

 

  

Golang协程特性实践

- go发起一个协程

- channel协程间通信,通道

- buffered channels具备缓冲队列的通道

 

go协程和channel初次使用

package main

import (
"fmt"
)

func main() {
    message := make(chan string)//定义一个string型的channel
    go func() {
        message <- "hello goroutine!"
    }()
    
    fmt.Println( <- message )
    fmt.Println("Hello world!")
}

 

多个协程

package main

import (
    "fmt"
    "time"
)

func main() {
    message := make(chan string) //定义一个string型的channel
    go func() {
        message <- "hello goroutine!"
    }()
    go func() {
        time.Sleep(2 * time.Second)
        str := <-message
        str = str + "I'm goroutine!"
        message <- str
    }()
    time.Sleep(3 * time.Second)
    fmt.Println(<-message)
    fmt.Println("Hello world!")
}

 

  

  

 

相关文章:

  • 2022-12-23
  • 2021-07-19
  • 2021-12-10
  • 2021-10-02
  • 2022-02-09
  • 2022-12-23
猜你喜欢
  • 2021-11-10
  • 2022-12-23
  • 2021-11-04
  • 2021-07-14
  • 2022-12-23
  • 2022-12-23
  • 2021-09-01
相关资源
相似解决方案