35

Golang goroutine和chan 教程01

 4 years ago
source link: https://www.tuicool.com/articles/URfINnn
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

goroutine是go语言的精髓,chan是实现goroutine的必要条件

首先我们要清楚的是,区分并发和并行。然后我们再来讨论goroutine对于并发的重要性。看以下代码。

package main

import (
    "fmt"
    "time"
)

func main() {
    go spiner(100*time.Millisecond)
    const n = 45
    fibN := fib(n)
    fmt.Printf("\r斐波那契(%d)=%d\n",n,fibN)
}

func spiner(delay time.Duration) {
    for  {
        for _, r := range `-\|/` {
            fmt.Printf("\r%c",r)
            time.Sleep(delay)
        }

    }

}

func fib(x int) int {
    if x < 2 {
        return x
    }
    return fib(x-1)+fib(x-2)
}
函数 执行体 spiner go spiner(100*time.Millisecond) fib fibN := fib(n)

这里使用了一个go关键字来对spiner函数执行并发。并在main函数执行结束的时候,结束所有函数的运行。这个程序的特点是,有两个独立的func在同时运行。

  • 当Main函数返回,所有的goroutine将暴力终结。(无论你在做什么)
  • goroutine最好要书写成自我生存的形式(自己在main返回之前安全的死亡)

看了这个例子,我们来看一下go这个关键字。

在《go程序设计语言》第八章中说道,在go中,每一个并发执行的活动都被称为goroutine,他类似于线程。但是他和线程的数量上有重大差别。更像是一种协程。(关于协程的内容我们会在之后的教程中讲到)

当一个程序启动的时候,只有一个goroutine来调用main函数,他的名字是主gouroutine。新的goroutine由go关键字创建,就是普通的函数加上go前缀。go语句本身的执行立即完成。剩下的都交给了并发的goroutine来决定的执行。

接下来讨论本章涉及到的代码:

// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64

time包中的Duration类型 实际上是int64,表示的是时间。最大的值是290年。

// Sleep pauses the current goroutine for at least the duration d.
// A negative or zero duration causes Sleep to return immediately.
func Sleep(d Duration)

一个睡眠函数,睡眠的时间是duration参数

总而言之这个小案例的代码还是比较简单滴。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK