goProject/trunk/goutil/routineCtrlUtil/routineCtrl_test.go
皮蛋13361098506 1b77f62820 初始化项目
2025-01-06 16:01:02 +08:00

49 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package routineCtrlUtil
import (
"fmt"
"testing"
"time"
)
func TestRoutineCtrl(t *testing.T) {
rtCtrl := New(3)
for i := 0; i < 10; i++ {
// 闭包函数避坑注意!!!
// 本段代码有坑,请特别注意!!!
// *** 待执行函数引用外变变量i程序可能会出现不符合逻辑的结果(外部变量变化时,闭包函数获取到的是变化后的变量值) ***
//rtCtrl.Run(func(arg interface{}) {
// fmt.Println(".", i)
// time.Sleep(time.Second * 1)
// fmt.Println("*", i)
// panic("111")
//}, nil)
//-------------------------------------------------
// 以下两种方式为正确示例:
// 避坑方式一:将闭包内使用的外部变量作为参数传入
// 将待执行函数内使用的外部变量,用参数传入,可避免不符合逻辑的结果
//rtCtrl.Run(func(arg interface{}) {
// ii, _ := arg.(int)
// fmt.Println(".", ii)
// time.Sleep(time.Second * 1)
// fmt.Println("*", ii)
// panic("111")
//}, i)
// 避坑方式二:将闭包内使用的外部变量固定下来,不让其再被修改
temp := i // 这种方式将产生一个局变变量temp并且temp不会被修改
rtCtrl.Run(func(arg interface{}) {
fmt.Println(".", temp)
time.Sleep(time.Second * 1)
fmt.Println("*", temp)
panic("111")
}, nil)
}
rtCtrl.Wait()
fmt.Println("\n==============")
}