amuz.es/src/infra/goutils@v0.1.3/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	mys "amuz.es/src/infra/goutils/sync"
     6  	"sync"
     7  	"time"
     8  	"math/rand"
     9  )
    10  
    11  type philosopher struct {
    12  	eating bool
    13  	left   *philosopher
    14  	right  *philosopher
    15  	//table
    16  }
    17  
    18  var current []int
    19  
    20  func anotherRoutine(cond *sync.Cond, j int) {
    21  	vb := time.Duration(rand.Intn(10)+1000) * time.Millisecond
    22  	time.Sleep(vb)
    23  	cond.L.Lock()
    24  	defer cond.L.Unlock()
    25  	cond.Wait()
    26  	current = append(current, j)
    27  }
    28  func monitor(cond *sync.Cond, i int, doneChan chan<- struct{}) {
    29  	defer close(doneChan)
    30  	j := 0
    31  	for {
    32  		cond.L.Lock()
    33  		if j == len(current) {
    34  			cond.Signal()
    35  		} else {
    36  			j++
    37  			//fmt.Printf("%d\n", current[j-1:j])
    38  			fmt.Printf("%d\n", j)
    39  			//fmt.Println(current)
    40  		}
    41  		cond.L.Unlock()
    42  		if i == j {
    43  			return
    44  		}
    45  	}
    46  }
    47  func main() {
    48  	i := 10000
    49  	doneChan := make(chan struct{})
    50  	cond := sync.NewCond(&mys.ReentrantMutex{})
    51  	go monitor(cond, i, doneChan)
    52  
    53  	for j := 0; j < i; j++ {
    54  		go anotherRoutine(cond, j)
    55  	}
    56  
    57  	<-doneChan
    58  	fmt.Printf("done %d\n", len(current))
    59  }