github.com/dearplain/goloader@v0.0.0-20190107071432-2b1e47d74273/examples/schedule/schedule.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  	"sync"
     7  	"time"
     8  )
     9  
    10  func main() {
    11  
    12  	var ch = make(chan bool, 20000)
    13  	var begin = make(chan bool)
    14  	var closeCh = make(chan bool)
    15  
    16  	w := sync.WaitGroup{}
    17  
    18  	w.Add(1)
    19  	go func() {
    20  		defer logPanic()
    21  		runtime.LockOSThread()
    22  		<-begin
    23  		fmt.Println("begin")
    24  		tm := time.Now()
    25  		for i := 0; i < 10000000; i++ {
    26  			<-ch
    27  		}
    28  		fmt.Println(time.Now().Sub(tm))
    29  		close(closeCh)
    30  		w.Done()
    31  	}()
    32  
    33  	for i := 0; i < 50000; i++ {
    34  		w.Add(1)
    35  		go func() {
    36  			defer logPanic()
    37  			var count int
    38  			load := 100
    39  			for {
    40  				count++
    41  				re := fmt.Sprint("haha")
    42  				if re == "haha" && count >= load {
    43  					count = 0
    44  					runtime.Gosched()
    45  				}
    46  				select {
    47  				case <-closeCh:
    48  					w.Done()
    49  					return
    50  				default:
    51  				}
    52  			}
    53  		}()
    54  	}
    55  
    56  	for i := 0; i < 20; i++ {
    57  		w.Add(1)
    58  		go func() {
    59  			defer logPanic()
    60  			for {
    61  				select {
    62  				case <-closeCh:
    63  					w.Done()
    64  					return
    65  				case ch <- true:
    66  				}
    67  			}
    68  		}()
    69  	}
    70  
    71  	fmt.Println("all start")
    72  	begin <- true
    73  
    74  	w.Wait()
    75  }
    76  
    77  func logPanic() {
    78  	if r := recover(); r != nil {
    79  		trace := make([]byte, 1024)
    80  		count := runtime.Stack(trace, false)
    81  		fmt.Printf("Stack of %d bytes: %s\n", count, trace)
    82  	}
    83  }