GoLang并发示例代码1(关于逻辑处理器运行顺序)

文章目录

    • [一开始我也不知道为什么多次go run都是先运行第二个goroutine](#一开始我也不知道为什么多次go run都是先运行第二个goroutine)
go 复制代码
// This sample program demonstrates how to create goroutines and
// how the scheduler behaves.
package main

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

// main is the entry point for all Go programs.
func main() {
	// Allocate 1 logical processor for the scheduler to use.
	// 在多核机器上,如果不指定 GOMAXPROCS,默认会使用所有可用的处理器核。这里显式地将其设置为 1,使得所有的 goroutines 都在一个逻辑处理器上执行(即单线程调度)。
	// 限制调度器只使用一个 CPU 核心,即模拟单线程执行环境
	runtime.GOMAXPROCS(1)

	// wg is used to wait for the program to finish.
	// Add a count of two, one for each goroutine.
	// sync.WaitGroup 是用来等待一组 goroutine 完成的同步工具
	// WaitGroup 是一个计数器,在每个 goroutine 完成时调用 Done 方法,将计数器减少。调用 Wait() 会阻塞,直到计数器减到 0 为止。
	var wg sync.WaitGroup
	wg.Add(2)

	fmt.Println("Start Goroutines")

	// Declare an anonymous function and create a goroutine.
	go func() {
		// Schedule the call to Done to tell main we are done.
		defer wg.Done()

		// Display the alphabet three times
		for count := 0; count < 3; count++ {
			for char := 'a'; char < 'a' + 26; char++ {
				fmt.Printf("%c ", char)
			}
			fmt.Println()
		}
	}()

	// Declare an anonymous function and create a goroutine.
	go func() {
		// Schedule the call to Done to tell main we are done.
		defer wg.Done()

		// Display the alphabet three times
		for count := 0; count < 3; count++ {
			for char := 'A'; char < 'A'+26; char++ {
				fmt.Printf("%c ", char)
			}
			fmt.Println()
		}
	}()

	// Wait for the goroutines to finish.
	fmt.Println("Waiting To Finish")

	// wg.Wait() 会阻塞主线程,直到 WaitGroup 计数器归零(即所有 goroutines 都调用了 Done)
	wg.Wait()

	fmt.Println("\nTerminating Program")
}
bash 复制代码
root@GoLang:~/proj1/GoDistributeCache# go run /root/proj1/GoDistributeCache/example/test.go
Start Goroutines
Waiting To Finish
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 
a b c d e f g h i j k l m n o p q r s t u v w x y z 
a b c d e f g h i j k l m n o p q r s t u v w x y z 
a b c d e f g h i j k l m n o p q r s t u v w x y z 

Terminating Program
root@GoLang:~/proj1/GoDistributeCache# 

一开始我也不知道为什么多次go run都是先运行第二个goroutine


当改成runtime.GOMAXPROCS(2)每次运行结果就不一定相同顺序了

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
花间相见7 分钟前
【JAVA开发】—— HTTP常见请求方法
java·开发语言·http
楼田莉子9 分钟前
Linux系统小项目——“主从设计模式”进程池
linux·服务器·开发语言·c++·vscode·学习
走粥18 分钟前
选项式API与组合式API的区别
开发语言·前端·javascript·vue.js·前端框架
从此不归路19 分钟前
Qt5 进阶【7】网络请求与 REST API 实战:QNetworkAccessManager 深度应用
开发语言·c++·qt
changzehai23 分钟前
Rust + VSCode + probe-rs搭建stm32-rs嵌入式开发调试环境
vscode·后端·stm32·rust·嵌入式·probe-rs
终端域名28 分钟前
如何选择有利于品牌宣传的网站域名
java·后端·struts·数字货币域名·网站域名
拽着尾巴的鱼儿29 分钟前
Spring:定时任务@Scheduled cron 的实现原理
java·后端·spring
郑州光合科技余经理32 分钟前
源码部署同城O2O系统:中台架构开发指南
java·开发语言·后端·架构·系统架构·uni-app·php
阿波罗尼亚32 分钟前
Java框架中的分层架构
java·开发语言·架构
Marktowin34 分钟前
访问控制权限模型分析梳理
后端