github.com/rolandhe/saber@v0.0.4/example/semaphore/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/rolandhe/saber/gocc"
     6  	"log"
     7  	"sync"
     8  	"time"
     9  )
    10  
    11  func main() {
    12  	waitUntilChan()
    13  	start()
    14  }
    15  
    16  func start() {
    17  	ch := make(chan struct{})
    18  	v := 1
    19  	go func() {
    20  		fmt.Println(v)
    21  		ch <- struct{}{}
    22  	}()
    23  	v = 12
    24  	<-ch
    25  }
    26  
    27  func waitUntilChan() {
    28  	limit := gocc.NewDefaultSemaphore(500)
    29  	waiter := sync.WaitGroup{}
    30  	waiter.Add(1000)
    31  	for i := 0; i < 1000; i++ {
    32  		go func(id int) {
    33  			start := time.Now().UnixNano()
    34  			limit.Acquire()
    35  			waitTime := time.Now().UnixNano() - start
    36  			time.Sleep(time.Millisecond * 200)
    37  			log.Printf("g:%d,wait:%d\n", id, waitTime)
    38  			limit.Release()
    39  			waiter.Done()
    40  		}(i)
    41  	}
    42  	waiter.Wait()
    43  }