goroutine是Go编程语言中的轻量级执行线程。它类似于其他编程语言中的线程,但它由Go运行时而不是操作系统管理。Goroutines允许在程序中并发执行函数,并且它们被设计为高效且可扩展。

在Go中,程序从单个goroutine(执行 main 函数)开始。可以使用go关键字后跟函数调用来创建其他goroutine。这将启动一个新的goroutine,该goroutine与原始goroutine同时运行。

Goroutines是非常轻量级的,可以在一个程序中创建数千甚至数百万个goroutine,而不会产生明显的开销。这使得在 Go 中编写并发程序变得容易,这些程序利用了多个CPU 内核,并且可以同时执行许多任务。

由于goroutines由Go运行时管理,因此它们会自动调度,并且可以使用通道相互通信。这使得编写复杂的并发程序变得容易,而不必担心锁定和同步等低级细节。

Goroutines使用通道相互通信,这是Go语言的内置功能。通道为goroutines提供了一种相互发送和接收值的方法,它们用于同步对共享数据的访问。

Goroutines是Go语言的一个关键特性,它们广泛用于并发和并行程序的设计中。它们使编写既高效又易于推理的代码变得容易。

新的goroutine由go语句创建。

要将函数作为goroutine运行,请调用以go语句为前缀的函数。下面是示例代码块:

sum()     // 普通函数,主线程等待函数执行完
go sum()  // goroutine函数,立即继续执行其他方法

go关键字使函数调用立即返回,而函数开始作为goroutine在后台运行,程序的其余部分继续执行。每个Golang程序的main函数都是使用goroutine启动的,因此每个Golang程序至少运行一个 goroutine。

 

创建 Goroutines

在每次调用函数responseSize之前添加了go关键字。三个responseSize goroutines同时启动,三个调用http。获取也是同时进行的。程序不会等到一个响应返回后再发送下一个请求。因此,使用 goroutines 可以更快地打印三种响应大小。

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

func responseSize(url string) {
	fmt.Println("Step1: ", url)
	response, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Step2: ", url)
	defer response.Body.Close()

	fmt.Println("Step3: ", url)
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Step4: ", len(body))
}

func main() {
	go responseSize("https://www.golangprograms.com")
	go responseSize("https://coderwall.com")
	go responseSize("https://stackoverflow.com")
	time.Sleep(10 * time.Second)
}

输出

Step1:  https://www.golangprograms.com
Step1:  https://stackoverflow.com
Step1:  https://coderwall.com
Step2:  https://stackoverflow.com
Step3:  https://stackoverflow.com
Step4:  116749
Step2:  https://www.golangprograms.com
Step3:  https://www.golangprograms.com
Step4:  79551
Step2:  https://coderwall.com
Step3:  https://coderwall.com
Step4:  203842

我们添加了对时间的调用。在main函数中休眠,这可以防止goroutines在responseSize goroutines完成之前退出。睡眠会让程序睡10秒。

 

等待goroutines完成执行

同步sync包的WaitGroup类型用于等待程序完成从主函数启动的所有goroutine。它使用指定goroutines数量的计数器,Wait会阻止程序的执行,直到 aitGroup计数器为零。

Add方法用于向等待组添加计数器。

WaitGroup的Done方法是使用defer语句来递减WaitGroup计数器的。

WaitGroup类型的Wait方法等待程序完成所有goroutine。

Wait方法在main函数内部调用,该方法阻止执行,直到WaitGroup计数器达到零值并确保执行所有goroutine。

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"sync"
)

// 用于等待所有goroutine执行完
var wg sync.WaitGroup

func responseSize(url string) {
	// 用于通知waitGroup当前goroutine执行完毕
	defer wg.Done()

	fmt.Println("Step1: ", url)
	response, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Step2: ", url)
	defer response.Body.Close()

	fmt.Println("Step3: ", url)
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Step4: ", len(body))
}

func main() {
	// 告诉wg有3个goroutine需要等待
	wg.Add(3)
	fmt.Println("Start Goroutines")

	go responseSize("https://www.golangprograms.com")
	go responseSize("https://stackoverflow.com")
	go responseSize("https://coderwall.com")

	// 主线程等待所有goroutine执行完毕
	wg.Wait()
	fmt.Println("Terminating Program")
}

输出

Start Goroutines
Step1:  https://coderwall.com
Step1:  https://www.golangprograms.com
Step1:  https://stackoverflow.com
Step2:  https://stackoverflow.com
Step3:  https://stackoverflow.com
Step4:  116749
Step2:  https://www.golangprograms.com
Step3:  https://www.golangprograms.com
Step4:  79801
Step2:  https://coderwall.com
Step3:  https://coderwall.com
Step4:  203842
Terminating Program

 

从 Goroutines 获取值

从goroutine获取值的最自然方法是通道。通道是连接并发goroutines的管道。您可以将值从一个goroutine发送到通道中,并将这些值接收到另一个goroutine或同步函数中。

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"sync"
)

var wg sync.WaitGroup

func responseSize(url string, nums chan int) {
	defer wg.Done()

	response, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}

	nums <- len(body)
}

func main() {
	nums := make(chan int) // 声明一个无缓冲通道
	wg.Add(1)
	go responseSize("https://www.golangprograms.com", nums)
	fmt.Println(<-nums) // 冲通道中读取值
	wg.Wait()
	close(nums) // 关闭通道
}

输出

79655

 

控制Goroutine的程序

使用通道,我们可以执行和暂停goroutine的流程。通道通过充当goroutines之间的管道来处理此通信。

package main

import (
	"fmt"
	"sync"
	"time"
)

var i int

func work() {
	time.Sleep(250 * time.Millisecond)
	i++
	fmt.Println(i)
}

func routine(command <-chan string, wg *sync.WaitGroup) {
	defer wg.Done()
	var status = "Play"
	for {
		select {
		case cmd := <-command:
			fmt.Println(cmd)
			switch cmd {
			case "Stop":
				return
			case "Pause":
				status = "Pause"
			default:
				status = "Play"
			}
		default:
			if status == "Play" {
				work()
			}
		}
	}
}

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	command := make(chan string)
	go routine(command, &wg)

	time.Sleep(1 * time.Second)
	command <- "Pause"

	time.Sleep(1 * time.Second)
	command <- "Play"

	time.Sleep(1 * time.Second)
	command <- "Stop"

	wg.Wait()
}

输出

1
2
3
4
Pause
Play
5
6
7
8
9
Stop

 

使用原子函数修复竞争条件

由于对共享资源的访问不同步并尝试同时读取和写入该资源,因此会出现竞争条件。

原子函数提供低级锁定机制,用于同步对整数和指针的访问。原子函数通常用于修复竞争条件。

sync包下的atomic中的函数通过锁定对共享资源的访问来支持同步goroutine。

package main

import (
	"fmt"
	"runtime"
	"sync"
	"sync/atomic"
)

var (
	counter int32          
	wg      sync.WaitGroup
)

func main() {
	wg.Add(3)

	go increment("Python")
	go increment("Java")
	go increment("Golang")

	wg.Wait()
	fmt.Println("Counter:", counter)

}

func increment(name string) {
	defer wg.Done()

	for range name {
		atomic.AddInt32(&counter, 1)
		runtime.Gosched() // 让出当前goroutine执行权
	}
}

原子包中的AddInt32函数通过强制一次只有一个goroutine可以执行和完成此添加操作来同步整数值的添加。当goroutines尝试调用任何原子函数时,它们会自动与引用的变量同步。

请注意,如果将代码行atomic.AddInt32(&counter, 1)替换为counter++,然后您将看到以下输出:

C:\Golang\goroutines>go run -race main.go
==================
WARNING: DATA RACE
Read at 0x0000006072b0 by goroutine 7:
  main.increment()
      C:/Golang/goroutines/main.go:31 +0x76

Previous write at 0x0000006072b0 by goroutine 8:
  main.increment()
      C:/Golang/goroutines/main.go:31 +0x90

Goroutine 7 (running) created at:
  main.main()
      C:/Golang/goroutines/main.go:18 +0x7e

Goroutine 8 (running) created at:
  main.main()
      C:/Golang/goroutines/main.go:19 +0x96
==================
Counter: 15
Found 1 data race(s)
exit status 66

C:\Golang\goroutines>

输出

C:\Golang\goroutines>go run -race main.go
Counter: 15


 

使用Mutex定义关键部分

互斥锁用于围绕代码创建一个关键部分,以确保一次只有一个goroutine可以执行该代码部分。

package main

import (
	"fmt"
	"sync"
)

var (
	counter int32          
	wg      sync.WaitGroup 
	mutex   sync.Mutex     // 用于定义需要保护的代码块,指该部分代码块保证每次只有一个线程访问。
)

func main() {
	wg.Add(3)

	go increment("Python")
	go increment("Go Programming Language")
	go increment("Java")

	wg.Wait()
	fmt.Println("Counter:", counter)

}

func increment(lang string) {
	defer wg.Done()

	for i := 0; i < 3; i++ {
		mutex.Lock()
		{
			fmt.Println(lang)
			counter++
		}
		mutex.Unlock()
	}
}

输出

C:\Golang\goroutines>go run -race main.go
Python
Python
Python
Java
Java
Java
Go Programming Language
Go Programming Language
Go Programming Language
Counter: 9

C:\Golang\goroutines>

由对Lock()Unlock()的调用定义的关键部分可针对计数器变量有保护操作。