origin

While writing unit tests, I encountered a problem with function inlining. I did not intend to disable the use of inlining globally. I found that I could disable the use of //go:noinline. After solving the problem, I am curious about // GO usage scenarios, so I will summarize them here.

Simply put, //go tells the compiler what to do next. Note that there is no space between // and go.

The specific type

//go:noinline

Noinline disables the inline function

For more information on introversion, see the Go language introversion mechanism.

//go:nosplit

Nosplit skips stack overflow detection

We know that the cost of creating a Goroutine is very small, with an initial memory footprint of only 2k. As the function runs, variable memory may be dynamically increased. The Go runtime checks to see if the allocated memory is running out, and increases the memory appropriately before running out.

Declaring //go:nosplit can improve performance, but may cause stack overflow to fail.

//go:noescape

Noescape is used to forbid escape, and it must indicate a function that has only a declaration and no body.

Escape simply means that memory allocated on the stack is moved to the heap. If escape is disabled, the variable will be destroyed after the function completes execution, possibly with a null pointer.

//go:norace

Norace is used to skip race detection

If multiple coroutines write critical sections at the same time, static competition will occur.

So for example,

var sum int

func main(a) {
    go add()
    go add()
}

func add(a) {
    sum++
}
Copy the code

The go run -race main.go command uses -race to cause the compiler to report data race problems.

WARNING: DATA RACE
Read at 0x00c000140078 by goroutine 8:
  main.main.func1()
      /Users/p/Desktop/code/other/go-demo/main.go:63 +0x46

Previous write at 0x00c000140078 by goroutine 7:
  main.main.func1()
      /Users/p/Desktop/code/other/go-demo/main.go:63 +0x5c

Goroutine 8 (running) created at:
  main.main()
      /Users/p/Desktop/code/other/go-demo/main.go:66 +0x4d4

Goroutine 7 (finished) created at:
  main.main()
      /Users/p/Desktop/code/other/go-demo/main.go:65 +0x4be
==================
Found 1 data race(s)
Copy the code

Experience sharing:

Once there was a goroutine null pointer problem in the online environment. Due to the complex code, it took a long time to find the cause of the problem. If you use //go:norace, you may be able to easily locate the problem.

The resources

  • Go compiler “// Go :” details