Skip to content

runtime (js/wasm): avoid scheduler recursion #2178

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/runtime/runtime_wasm_js.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,20 @@ import "unsafe"

type timeUnit float64 // time in milliseconds, just like Date.now() in JavaScript

// wasmRunning is used to track whether wasm is currently running to avoid nested scheduling.
var wasmRunning bool

//export _start
func _start() {
wasmRunning = true

// These need to be initialized early so that the heap can be initialized.
heapStart = uintptr(unsafe.Pointer(&heapStartSymbol))
heapEnd = uintptr(wasm_memory_size(0) * wasmPageSize)

run()

wasmRunning = false
}

var handleEvent func()
Expand All @@ -24,15 +31,27 @@ func setEventHandler(fn func()) {

//export resume
func resume() {
prevRunning := wasmRunning
wasmRunning = true
go func() {
handleEvent()
}()
scheduler()
if !prevRunning {
// Nothing is currently running, so we can safely invoke the scheduler.
scheduler()
}
wasmRunning = prevRunning
}

//export go_scheduler
func go_scheduler() {
if wasmRunning {
return
}

wasmRunning = true
scheduler()
wasmRunning = false
}

func ticksToNanoseconds(ticks timeUnit) int64 {
Expand Down
14 changes: 13 additions & 1 deletion src/runtime/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,18 @@ func addSleepTask(t *task.Task, duration timeUnit) {
*q = t
}

var schedulerRunning bool

// Run the scheduler until all tasks have finished.
func scheduler() {
// Main scheduler loop.
if schedulerDebug {
if schedulerRunning {
runtimePanic("nested scheduler")
}

schedulerRunning = true
}
var now timeUnit
for !schedulerDone {
scheduleLog("")
Expand All @@ -143,7 +152,7 @@ func scheduler() {
if sleepQueue == nil {
if asyncScheduler {
// JavaScript is treated specially, see below.
return
break
}
waitForEvents()
continue
Expand All @@ -170,6 +179,9 @@ func scheduler() {
scheduleLogTask(" run:", t)
t.Resume()
}
if schedulerDebug {
schedulerRunning = false
}
}

func Gosched() {
Expand Down