1. 创建goruoutine
func newTask() {
for {
fmt.Println("this is new task")
time.Sleep(time.Second) //延时1s
}
}
func main() {
go newTask() //❤️建一个协程,新建一个任务
for {
fmt.Println("this is a main goroutine")
time.Sleep(time.Second) //延时1s
}
}
输出
this is a main goroutine
this is new task
this is a main goroutine
this is new task
this is new task
this is a main goroutine
this is new task
this is a main goroutine
this is new task
this is a main goroutine
this is new task
this is a main goroutine
this is new task
this is a main goroutine
this is new task
this is a main goroutine
this is new task
this is a main goroutine
2. 主协程先退出,其它子协程夜会跟着退出
//主协程退出了,其它子协程也要跟着退出
func main() {
go func() {
fmt.Println("this is a new task")
time.Sleep(time.Second)
}() //() 代表调用
i :=0
for {
i++
fmt.Println("main this is a main task i=", i)
time.Sleep(time.Second)
if i == 3 {
break
}
}
}
3. runtime.Gosched
让出时间片,先让别的协程执行,它执行完,在回来执行此协程
func main() {
go func() {
for {
fmt.Println("this is new task")
}
}()
for i:=0; i<5; i++ {
//让出时间片,先让别的协程执行,它执行完,在回来执行此协程
runtime.Gosched()
fmt.Println("this is main task i=", i)
}
}
4. runtime.Goexit
终止所在的协程
func main() {
go func() {
for i:=0; i<5; i++ {
fmt.Println("this is a new task, i=", i)
time.Sleep(time.Second)
if i == 3 {
runtime.Goexit() //终止所在的协程
}
}
}()
//死循环,目的不让主协程退出
for {
}
}
5. runtime.GOMAXPROCS
指定以x核运算
func main() {
runtime.GOMAXPROCS(4) //指定以x核运算
go func() {
for {
fmt.Print(1)
}
}()
for {
fmt.Print(0)
}
}