您的当前位置:首页正文

Go语言的使用Goroutine

2024-11-30 来源:个人技术集锦

并发和并行的差别:并发就是同时处理很多事情,而并行就是同时做很多事情。(较难理解)

模拟阻塞的函数调用,程序清单如下:

package main

import(
  "fmt"
  "time"
)
func slowFunc(){
  time.Sleep(time.Second*2)        //暂停2秒
  fmt.Println("sleeper() finished")
}
func main(){
  slowFunc()
  fmt.Println("I am not shown until slowFunc() completes")
}

运行结果如下:

sleeper() finished
I am not shown until slowFunc() completes

使用Goroutine,程序清单如下:

package main

import(
  "fmt"
  "time"
)
func slowFunc(){
  time.Sleep(time.Second*2)
  fmt.Println("sleeper() finished")
}
func main(){
  go slowFunc()
  fmt.Println("I am not shown until slowFunc() completes")
}

运行结果如下:

I am not shown until slowFunc() completes

使用Goroutine来实现并发执行,程序清单如下:

package main

import(
  "fmt"
  "time"
)
func slowFunc(){
  time.Sleep(time.Second*2)
  fmt.Println("sleeper() finished")
}
func main(){
  go slowFunc()
  fmt.Println("I am not shown until slowFunc() completes")
  time.Sleep(time.Second*3)
}

运行结果如下:(中间过段时间)

I am not shown until slowFunc() completes
sleeper() finished

显示全文