defer_in_loop.mx raw

   1  // A defer inside a loop registers ONCE PER ITERATION and runs once each, in
   2  // reverse order, when the function returns.
   3  //
   4  // The defect this pins: the deferred record was a single stack alloca, so every
   5  // iteration re-pushed the same slot, the defer chain chained to itself, and the
   6  // loop case died before it could even spin - "alloc: implausible size
   7  // 2147483648", a sign-extended capacity. The record is now allocated per
   8  // execution from the function's arena, which is reclaimed with the frame after
   9  // the deferred calls have run.
  10  package main
  11  
  12  import (
  13  	"fmt"
  14  	"os"
  15  )
  16  
  17  type log struct {
  18  	vals []int32
  19  }
  20  
  21  func (l *log) note(v int32) {
  22  	l.vals = push(l.vals, v)
  23  }
  24  
  25  // loopDefers registers three defers inside a loop.
  26  func loopDefers() (l *log) {
  27  	l = &log{}
  28  	for i := int32(0); i < 3; i++ {
  29  		defer l.note(i)
  30  	}
  31  	return l
  32  }
  33  
  34  // plainDefers is the control: two defers outside any loop.
  35  func plainDefers() (l *log) {
  36  	l = &log{}
  37  	defer l.note(10)
  38  	defer l.note(11)
  39  	return l
  40  }
  41  
  42  func main() {
  43  	// Termination: a batch program must still be stoppable, so the entry
  44  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  45  	select {
  46  	case <-shutdown:
  47  		return
  48  	default:
  49  	}
  50  
  51  	var fails int32
  52  
  53  	l := loopDefers()
  54  	if len(l.vals) != 3 {
  55  		fmt.Printf("FAIL loop: len=%d want 3\n", int32(len(l.vals)))
  56  		fails = fails + 1
  57  	} else if l.vals[0] != 2 || l.vals[1] != 1 || l.vals[2] != 0 {
  58  		fmt.Printf("FAIL loop order: %d %d %d want 2 1 0\n", l.vals[0], l.vals[1], l.vals[2])
  59  		fails = fails + 1
  60  	} else {
  61  		fmt.Printf("ok   loop defers: 3 registrations, reverse order\n")
  62  	}
  63  
  64  	p := plainDefers()
  65  	if len(p.vals) != 2 || p.vals[0] != 11 || p.vals[1] != 10 {
  66  		if len(p.vals) == 2 {
  67  			fmt.Printf("FAIL plain order: %d %d want 11 10\n", p.vals[0], p.vals[1])
  68  		} else {
  69  			fmt.Printf("FAIL plain: len=%d want 2\n", int32(len(p.vals)))
  70  		}
  71  		fails = fails + 1
  72  	} else {
  73  		fmt.Printf("ok   plain defers: reverse order\n")
  74  	}
  75  
  76  	if fails != 0 {
  77  		fmt.Printf("defer_in_loop: %d wrong\n", fails)
  78  		os.Exit(1)
  79  	}
  80  	fmt.Printf("defer_in_loop ok\n")
  81  }
  82