From 34407f0dfe5e43453024b76ad8977ac9488978e3 Mon Sep 17 00:00:00 2001 From: Administrator Date: Wed, 3 Jul 2024 18:35:02 +0800 Subject: [PATCH] concurrency study --- Concurrency/Concurrency | 2 ++ Concurrency/Concurrency.go | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/Concurrency/Concurrency b/Concurrency/Concurrency index 25444cf..040d3f1 100644 --- a/Concurrency/Concurrency +++ b/Concurrency/Concurrency @@ -7,3 +7,5 @@ golang的并发通过goroutine实现,goroutine是用户态的线程,由go的 最终还是放在操作系统的线程去执行,只不过管理(上下文切换)放在用户态,所以开销较小。 golang提供channel用来在多个goroutine之间进行通信。 + +通过go 关键字来开启一个goroutine diff --git a/Concurrency/Concurrency.go b/Concurrency/Concurrency.go index 7905807..6c0b270 100644 --- a/Concurrency/Concurrency.go +++ b/Concurrency/Concurrency.go @@ -1,5 +1,25 @@ package main +import ( + "fmt" + "time" +) + +func hello() { + fmt.Println("hello") +} + +// 主goroutine开启,之后所有的子协程都会自行退出 func main() { + //通过匿名函数开启goroutine + for i := 0; i < 10; i++ { + go func() { + fmt.Println(i) + }() //事实上这个函数中的i去找到的是上面这个循环的i,所以当goroutine启动过快有可能在一个循环中找到i + + } + fmt.Println("this is main,2") + time.Sleep(time.Second) + }