sisosIIgolang20101
[3hU9fRjo95.git] / pc_monitor_sem.go~
blobf53cc4331835421ba89368a462f4daa9ebb73684
1 /* main */
2 package main
4 import (
5         . "fmt"
6         "crypto/rand"
7         "time"
8         "flag"
11 type Monitor struct {
12         mutex chan int
13         empty chan int
14         full    chan int
15         buffer []int
16         front int
17         rear int
20 func rand_between(begin, end int64) int64 {
21         b := make([]byte, 1)
22         rand.Read(b)
23         return int64(b[0]) % (end - begin + 1) + begin
26 func (m Monitor) produz(i int) {
27         <-m.empty
28         <-m.mutex
29                 Println("produzindo:", i)
31                 m.buffer[m.rear] = i
32                 m.rear = (m.rear + 1) % *BUFFER_SIZE
33         m.mutex <- 0
34         m.full  <- 0
37 func (m Monitor) consome() {
38                 var v int
40                 <-m.full
41                 <-m.mutex
42                         v = m.buffer[m.front]
43                         m.front = (m.front + 1) % *BUFFER_SIZE
44         
45                         Println("\tconsumindo:", v)
46                 m.mutex <- 0
47                 m.empty <- 0
50 var BUFFER_SIZE = flag.Int("s", 5, "BUFFER_SIZE")
51 const SLEEP_TIME = 5
53 func newMonitor() Monitor {
54         mutex := make(chan int, 1)
55         empty := make(chan int, *BUFFER_SIZE)
57         for i := 0; i < *BUFFER_SIZE; i++ {
58                 empty <- 0
59         }
60         mutex <- 0
62         return Monitor {
63                 mutex,
64                 empty,
65                 make(chan int, *BUFFER_SIZE),
66                 make([]int, *BUFFER_SIZE),
67                 0,
68                 0 }
71 func produtor() {
72         for i := 0; ; i++ {
73                 monitor.produz(i)
75                 time.Sleep(rand_between(0, SLEEP_TIME) * 10e7)
76         }
79 func consumidor(end chan<- int) {
80         for {
81                 monitor.consome()
83                 time.Sleep(rand_between(0, SLEEP_TIME) * 10e7)
84         }
85         end <- 0
88 var monitor = newMonitor()
90 func main() {
91         flag.Parse()
92         Println("BUFFER_SIZE=", *BUFFER_SIZE)
93         
94         end := make(chan int)
95         go produtor()
96         go consumidor(end)
97         <-end