Skip to content

Commit 2718130

Browse files
committed
mainthread: optimize memory usage
name old time/op new time/op delta Call-16 3.08µs ±0% 2.98µs ±0% -3.23% (p=0.000 n=9+9) name old alloc/op new alloc/op delta Call-16 120B ±0% 24B ±0% -80.00% (p=0.000 n=10+10) name old allocs/op new allocs/op delta Call-16 2.00 ±0% 1.00 ±0% -50.00% (p=0.000 n=10+10)
1 parent 42099d4 commit 2718130

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

mainthread.go

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44

55
package mainthread // import "golang.design/x/mainthread"
66

7-
import "runtime"
7+
import (
8+
"runtime"
9+
"sync"
10+
)
811

912
var funcQ = make(chan func(), runtime.GOMAXPROCS(0))
1013

@@ -17,7 +20,9 @@ func init() {
1720
//
1821
// Init must be called in the main package.
1922
func Init(main func()) {
20-
done := make(chan struct{})
23+
done := donePool.Get().(chan struct{})
24+
defer donePool.Put(done)
25+
2126
go func() {
2227
defer func() {
2328
done <- struct{}{}
@@ -37,7 +42,9 @@ func Init(main func()) {
3742

3843
// Call calls f on the main thread and blocks until f finishes.
3944
func Call(f func()) {
40-
done := make(chan struct{})
45+
done := donePool.Get().(chan struct{})
46+
defer donePool.Put(done)
47+
4148
funcQ <- func() {
4249
defer func() {
4350
done <- struct{}{}
@@ -46,3 +53,7 @@ func Call(f func()) {
4653
}
4754
<-done
4855
}
56+
57+
var donePool = sync.Pool{
58+
New: func() interface{} { return make(chan struct{}) },
59+
}

0 commit comments

Comments
 (0)