Go语言教程之边写边学:基础练习:如何创建多个goroutine,如何使用三个逻辑处理器

Go标准库在运行时包中有一个名为GOMAXPROCS的函数,它允许我们指定调度程序要使用的逻辑处理器的数量。

如果我们为调度程序提供多个逻辑处理器来使用,我们将在示例程序的输出中看到不同的行为。如果你运行这个程序,你会看到goroutines是并行运行的。多个goroutine开始运行,显示中的字母和数字是混合的。输出基于在八核机器上运行程序,因此每个goroutine都在自己的内核上运行。

package main

import (
	"fmt"
	"runtime"
	"sync"
)

func main() {
	// Allocate three logical processors for the scheduler to use.
	runtime.GOMAXPROCS(3)

	// processTest is used to wait for the program to finish.
	var processTest sync.WaitGroup
	// Add a count of three, one for each goroutine.
	processTest.Add(3)
	
	// Declaration of three anonymous function and create a goroutine.
	go func() {
		defer processTest.Done()
		for i := 0; i < 30; i++ {
			for j := 51; j <= 100; j++ {
				fmt.Printf(" %d", j)
				if j == 100{
					fmt.Println()
				}
			}
		}
	}()
	go func() {
		defer processTest.Done()
		for j := 0; j < 10; j++ {
			for char := 'A'; char < 'A'+26; char++ {
				fmt.Printf("%c ", char)
				if char == 'Z' {
					fmt.Println()
				}

			}
		}
	}()
	go func() {
		defer processTest.Done()
		for i := 0; i < 30; i++ {
			for j := 0; j <= 50; j++ {
				fmt.Printf(" %d", j)
				if j == 50 {
					fmt.Println()
				}
			}
		}
	}()

	// Wait for the goroutines to finish.
	processTest.Wait()	
}