goroutine下的test1和test2
This commit is contained in:
parent
952dcf9e12
commit
bba7ffe503
29
bilibili/aceld/goroutine/test1/main.go
Normal file
29
bilibili/aceld/goroutine/test1/main.go
Normal file
@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newTask() {
|
||||
i := 0
|
||||
for {
|
||||
i++
|
||||
fmt.Printf("new Goroutin: i = %d\n", i)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 创建一个go程去执行newTask()流程
|
||||
go newTask()
|
||||
// 如果直接打印一句话并退出,那么整个进程都结束了,go程也就随着结束了
|
||||
fmt.Println("main goroutine exit")
|
||||
// 如果进程继续运行,那么go程才可以进行执行
|
||||
// i := 0
|
||||
// for {
|
||||
// i++
|
||||
// fmt.Printf("main goroutio: i = %d\n", i)
|
||||
// time.Sleep(1 * time.Second)
|
||||
// }
|
||||
}
|
34
bilibili/aceld/goroutine/test2/main.go
Normal file
34
bilibili/aceld/goroutine/test2/main.go
Normal file
@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 用go创建承载一个形参为空,返回值为空的一个函数
|
||||
// go func() {
|
||||
// defer fmt.Println("A.defer")
|
||||
// // 如果go程强制退出
|
||||
// // return
|
||||
|
||||
// func() {
|
||||
// defer fmt.Println("B.defer")
|
||||
// // 直接return,只会退出当前子函数,并没有退出goroutin
|
||||
// // return
|
||||
// // 用runtion.Goexit()会退出当前goroutine(效果就是fmt.Println("A")不会被执行)
|
||||
// runtime.Goexit()
|
||||
// fmt.Println("B")
|
||||
// }() // 结尾的小括号表示定义匿名函数后立即调用这个函数
|
||||
// fmt.Println("A")
|
||||
// }()
|
||||
|
||||
go func(a int, b int) bool {
|
||||
fmt.Println("a = ", a, ", b = ", b)
|
||||
return false
|
||||
}(10, 20)
|
||||
|
||||
for {
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user