tudo pronto
[3hU9fRjo95.git] / pc_mutex.go
blob8759185dca76be731b5aa6d14b0774af4cf9bd47
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
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
43 func producer () {
44 for i := 0; ; i++ { // laço infinito
45 for count == BUFFER_SIZE { // buffer cheio?
46 random_sleep() // (almost) busy wait
48 mutex.Lock()
49 if count < BUFFER_SIZE {
50 Println("producing:", i)
51 buffer[rear] = i
52 rear = (rear + 1) % BUFFER_SIZE
53 count++
54 } else {
55 i--
57 mutex.Unlock()
58 random_sleep()
62 func consumer () {
63 for { // laço infinito
64 for count == 0 { // buffer vazio?
65 random_sleep() // (almost) busy wait
67 mutex.Lock()
68 if count > 0 {
69 v := buffer[front]
70 front = (front + 1) % BUFFER_SIZE
71 count--
72 Println("\t\t\tconsuming:", v)
74 mutex.Unlock()
75 random_sleep()
79 func main () {
80 buffer = make([]int, BUFFER_SIZE)
81 go producer()
82 go consumer()
83 wait(make(chan int)) // espera indefinidamente