Skip to content

Commit

Permalink
add alternative used to benchmark
Browse files Browse the repository at this point in the history
  • Loading branch information
ldemailly committed Jul 16, 2024
1 parent eeef157 commit a9bec02
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
4 changes: 4 additions & 0 deletions goroutine/gid.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
//go:build !tinygo

package goroutine

import (
"github.com/kortschak/goroutine" // Rely on and forward to the original rather than maintain our own copy.
)

const IsTinyGo = false

// ID returns the runtime ID of the calling goroutine.
func ID() int64 {
return goroutine.ID()
Expand Down
15 changes: 13 additions & 2 deletions goroutine/gid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@ func TestID(t *testing.T) {
if got != want {
t.Fatalf("unexpected id for main goroutine: got:%d want:%d", got, want)
}
n := 1000000 // for regular go
if IsTinyGo {
n = 1000 // for tinygo
}
var wg sync.WaitGroup
for i := 0; i < 1000000; i++ {
for i := 0; i < n; i++ {
i := i
wg.Add(1)
go func() {
Expand All @@ -35,8 +39,14 @@ func TestID(t *testing.T) {
wg.Wait()
}

var testID int64

// goid returns the goroutine ID extracted from a stack trace.
func goid() int64 {
if IsTinyGo {
testID++
return testID // pretty horrible test that aligns with the implementation, but at least it tests we get 1,2,3... different numbers.
}
var buf [64]byte
n := runtime.Stack(buf[:], false)
idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
Expand All @@ -47,8 +57,9 @@ func goid() int64 {
return id
}

var gotid int64

func BenchmarkGID(b *testing.B) {
var gotid int64
for n := 0; n < b.N; n++ {
gotid += ID()
}
Expand Down
34 changes: 34 additions & 0 deletions goroutine/gid_tinygo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//go:build tinygo

package goroutine

import (
"sync"
"unsafe"
)

const IsTinyGo = true

var (
counter int64
mapping = make(map[uintptr]int64)
lock sync.Mutex
)

func ID() int64 {
task := uintptr(currentTask())
lock.Lock()
if id, ok := mapping[task]; ok {
lock.Unlock()
return id
}
counter++
mapping[task] = counter
lock.Unlock()
return counter
// or, super fast but ugly large numbers/pointers:
//return int64(uintptr(currentTask()))
}

//go:linkname currentTask internal/task.Current
func currentTask() unsafe.Pointer

0 comments on commit a9bec02

Please sign in to comment.