Public
Snippet $224 authored by Kirill Smelkov

//go:linkname to get access to e.g. Go runtime internals

Edited
stoptheworld.go
/*
Stoptheworld program demonstrates how to call functions private to Go runtime,
or any other package, on the example of stopping the world.

This program must be accompanied with the following file to build correctly:
---- 8< ---- (stw.s)
// empty .s so that go build does not use -complete for go:linkname to work
---- 8< ----
*/
package main

import (
        "fmt"
        "time"
        _ "unsafe"
)

//go:linkname runtime_stopTheWorld runtime.stopTheWorld
func runtime_stopTheWorld(string)

//go:linkname runtime_startTheWorld runtime.startTheWorld
func runtime_startTheWorld()

func ticker(name string) {
        for range time.Tick(time.Second / 4) {
                println("tick", name)
        }
}

var j int

func main() {
        go ticker("α")
        go ticker("β")

        time.Sleep(2*time.Second)
        tstop := time.Now()
        fmt.Printf("\nstopping the world @ %v\n", tstop)
        runtime_stopTheWorld("just for my reason")

        // busywait, because time.Sleep will cause
        //      "fatal error: releasep: invalid p state"
        // under world stopped
        for i := 0; i < 1e10; i++ {
                j = i
        }

        runtime_startTheWorld()
        trestart := time.Now()
        fmt.Printf("\nworld restarted @ %v   (was stopped for %v)\n\n", trestart, trestart.Sub(tstop))

        time.Sleep(2*time.Second)
        println("exit")
}