From 2e11c99b7ac8204f5e6fb7d2f396561665b18cc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E7=A5=A5=E8=B6=85?= Date: Tue, 14 Dec 2021 10:49:40 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/goman/lib.go | 28 ++++++++++++++++++++++++++++ internal/goman/lib_test.go | 7 +++++++ 2 files changed, 35 insertions(+) diff --git a/internal/goman/lib.go b/internal/goman/lib.go index fa0dbbb..0d0feaa 100644 --- a/internal/goman/lib.go +++ b/internal/goman/lib.go @@ -40,6 +40,34 @@ func New(f func()) { }() } +// NewWithArgs 创建带有参数的goroutine +func NewWithArgs(f func(args ...interface{}), args ...interface{}) { + _, file, line, _ := runtime.Caller(1) + + go func() { + locker.Lock() + instanceId++ + + var instance = &Instance{ + Id: instanceId, + CreatedTime: time.Now(), + } + + instance.File = file + instance.Line = line + + instanceMap[instanceId] = instance + locker.Unlock() + + // run function + f(args...) + + locker.Lock() + delete(instanceMap, instanceId) + locker.Unlock() + }() +} + // List 列出所有正在运行goroutine func List() []*Instance { locker.Lock() diff --git a/internal/goman/lib_test.go b/internal/goman/lib_test.go index 622a91f..11358d1 100644 --- a/internal/goman/lib_test.go +++ b/internal/goman/lib_test.go @@ -19,3 +19,10 @@ func TestNew(t *testing.T) { time.Sleep(1 * time.Second) } + +func TestNewWithArgs(t *testing.T) { + NewWithArgs(func(args ...interface{}) { + t.Log(args[0], args[1]) + }, 1, 2) + time.Sleep(1 * time.Second) +}