done with the source
[3hU9fRjo95.git] / pc_mutex.go~
blob9a9a7744a6bad42e38a7e65a48968d667fa339e0
1 /* pc_mutex */
3 package main
5 import (
6         . "fmt"
7         "crypto/rand"
8         "time"
9         . "sync"
12 func random_entre (begin, end int64) int64 {
13         random_byte := make([]byte, 1)
14         rand.Read(random_byte)
15         return int64(random_byte[0]) % (end - begin + 1) + begin
18 func random_sleep () {
19         time.Sleep(random_entre(0, MAX_SLEEP_TIME) * 10e7)
22 func signal (channel chan int) {
23         if len(channel) < cap(channel) || cap(channel) == 0 {
24                 channel <- 0
25         }
28 func wait (channel chan int) {
29         <-channel
32 func produtor () {
33         for i := 0; ; i++ {
34                 for count == BUFFER_SIZE {
35                         random_sleep()
36                 }
38                 mutex.Lock()
39                         if count < BUFFER_SIZE  {
40                                 Println("produzindo:", i)
41                                 buffer[rear] = i
42                                 rear = (rear + 1) % BUFFER_SIZE
43                                 count++
44                         } else {
45                                 i--
46                         }
47                 mutex.Unlock()
49                 random_sleep()
50         }
51         signal(quit)
54 func consumidor () {
55         for {
56                 for count == 0 {
57                         random_sleep()
58                 }
60                 mutex.Lock()
61                         if count > 0 {
62                                 v := buffer[front]
63                                 front = (front + 1) % BUFFER_SIZE
64                                 count--
65                                 Println("\tconsumindo:", v)
66                         }
67                 mutex.Unlock()
69                 random_sleep()
70         }
73 const (
74         MAX_SLEEP_TIME = 5
75         BUFFER_SIZE = 5
78 var (
79         mutex = new(Mutex)
80         buffer []int
81         count = 0
82         front = 0
83         rear    = 0
86 func main () {
87         buffer = make([]int, BUFFER_SIZE)
88         go produtor()
89         go consumidor()
90         wait(make(chan int))