Go Goroutine

如何使用Goroutine在基于Go的程序中,提升你程序执行的性能。

使用Goroutine是一个非常快速简单的,转变一个顺序的程序到一个并发的程序,而不用担心在传统语言如Python,Java中,需要做的事情例如创建线程或者线程工具。

与所有的并发语言一样有内在的固有的危险,go关键字在所有的函数调用之前。

首先,什么是Goroutine。

Goroutine是由Go运行时管理的轻量级的线程,它让我们能够创建异步的并行程序。

可以执行一些任务比写成顺序形势要快得多。Goroutine是多路的在一个小数量的OS线程中。

意味着一般并发Go程序需要更少的资源,为了提供相同级别的性能如Java。

创建一千个Goroutine一般需要最多一到两个系统线程,如果在Java中做相同的事情将需要1000个完整的线程,每个最少占据1Mb的堆空间。

通过映射成百上千的goroutines到一个线程中,我们不需要考虑性能当在应用中创建和销毁线程时。难以置信的便宜当创建和销毁新的goroutines时,因为它们的大小和go处理它们的高效方式。

顺序代码

package main


import (
    "fmt"
    "time"
)


// a very simple function that we'll
// make asynchronous later on
func compute(value int) {
    for i := 0; i < value; i++ {
        time.Sleep(time.Second)
        fmt.Println(i)
    }
}

func main() {
    fmt.Println("Goroutine Tutorial")

    // sequential execution of our compute function
    compute(10)
    compute(10)

    // we scan fmt for input and print that to our console
    var input string
    fmt.Scanln(&input)

}

异步

package main


import (
    "fmt"
    "time"
)

// notice we've not changed anything in this function
// when compared to our previous sequential program
func compute(value int) {
    for i := 0; i < value; i++ {
        time.Sleep(time.Second)
        fmt.Println(i)
    }
}

func main() {
    fmt.Println("Goroutine Tutorial")

    // notice how we've added the 'go' keyword
    // in front of both our compute function calls
    go compute(10)
    go compute(10)

    var input string
    fmt.Scanln(&input)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值