github.com/TeaOSLab/EdgeNode@v1.3.8/internal/goman/lib.go (about) 1 // Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved. 2 3 package goman 4 5 import ( 6 teaconst "github.com/TeaOSLab/EdgeNode/internal/const" 7 "runtime" 8 "sync" 9 "time" 10 ) 11 12 var locker = &sync.Mutex{} 13 var instanceMap = map[uint64]*Instance{} // id => *Instance 14 var instanceId = uint64(0) 15 16 // New 新创建goroutine 17 func New(f func()) { 18 if !teaconst.IsMain { 19 return 20 } 21 22 _, file, line, _ := runtime.Caller(1) 23 24 go func() { 25 locker.Lock() 26 instanceId++ 27 28 var instance = &Instance{ 29 Id: instanceId, 30 CreatedTime: time.Now(), 31 } 32 33 instance.File = file 34 instance.Line = line 35 36 instanceMap[instanceId] = instance 37 locker.Unlock() 38 39 // run function 40 f() 41 42 locker.Lock() 43 delete(instanceMap, instanceId) 44 locker.Unlock() 45 }() 46 } 47 48 // NewWithArgs 创建带有参数的goroutine 49 func NewWithArgs(f func(args ...interface{}), args ...interface{}) { 50 if !teaconst.IsMain { 51 return 52 } 53 54 _, file, line, _ := runtime.Caller(1) 55 56 go func() { 57 locker.Lock() 58 instanceId++ 59 60 var instance = &Instance{ 61 Id: instanceId, 62 CreatedTime: time.Now(), 63 } 64 65 instance.File = file 66 instance.Line = line 67 68 instanceMap[instanceId] = instance 69 locker.Unlock() 70 71 // run function 72 f(args...) 73 74 locker.Lock() 75 delete(instanceMap, instanceId) 76 locker.Unlock() 77 }() 78 } 79 80 // List 列出所有正在运行goroutine 81 func List() []*Instance { 82 locker.Lock() 83 defer locker.Unlock() 84 85 var result = []*Instance{} 86 for _, instance := range instanceMap { 87 result = append(result, instance) 88 } 89 return result 90 }