tudo pronto
[3hU9fRjo95.git] / pc_mutex.go~
blobb9bac7c70562f7e222b8767057ba0852c5300343
1 /* pc_mutex */
3 package main
5 import (
6         . "fmt"
7         "crypto/rand"
8         "time"
9         . "sync"
12 func random_between (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_between(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 const (
33         MAX_SLEEP_TIME = 5 // tempo máximo de sleep
34         BUFFER_SIZE = 5          // tamanho do buffer
37 var (
38         mutex = new(Mutex)
39         buffer []int
40         count, front, rear = 0, 0, 0
41         //front = 0
42         //rear  = 0
45 func producer () {
46         for i := 0; ; i++ { // laço infinito
47                 for count == BUFFER_SIZE { // buffer cheio?
48                         random_sleep() // (almost) busy wait
49                 }
50                 mutex.Lock()
51                         if count < BUFFER_SIZE  {
52                                 Println("producing:", i)
53                                 buffer[rear] = i
54                                 rear = (rear + 1) % BUFFER_SIZE
55                                 count++
56                         } else {
57                                 i--
58                         }
59                 mutex.Unlock()
60                 random_sleep()
61         }
64 func consumer () {
65         for { // laço infinito
66                 for count == 0 { // buffer vazio?
67                         random_sleep() // (almost) busy wait
68                 }
69                 mutex.Lock()
70                         if count > 0 {
71                                 v := buffer[front]
72                                 front = (front + 1) % BUFFER_SIZE
73                                 count--
74                                 Println("\t\t\tconsuming:", v)
75                         }
76                 mutex.Unlock()
77                 random_sleep()
78         }
81 func main () {
82         buffer = make([]int, BUFFER_SIZE)
83         go producer()
84         go consumer()
85         wait(make(chan int)) // espera indefinidamente