tudo pronto
[3hU9fRjo95.git] / pc_sem.go
blob18ad208802137f6ee56042daf2fcd45da849e0f1
1 /* pc_sem.go */
3 package main
5 import (
6 . "fmt"
7 "crypto/rand"
8 "time"
11 func random_between (begin, end int64) int64 {
12 random_byte := make([]byte, 1)
13 rand.Read(random_byte)
14 return int64(random_byte[0]) % (end - begin + 1) + begin
17 func random_sleep () {
18 time.Sleep(random_between(0, MAX_SLEEP_TIME) * 10e7)
21 func signal (channel chan int) {
22 if len(channel) < cap(channel) || cap(channel) == 0 {
23 channel <- 0
27 func wait (channel chan int) {
28 <-channel
31 const (
32 MAX_SLEEP_TIME = 5
33 BUFFER_SIZE = 5
36 var (
37 mutex = make(chan int, 1);
38 empty, full chan int;
39 buffer []int;
40 front, rear = 0, 0
43 func producer () {
44 for i := 0; ; i++ { // laço infinito
45 wait(empty)
46 wait(mutex)
47 Println("producing:", i)
48 buffer[rear] = i
49 rear = (rear + 1) % BUFFER_SIZE
50 signal(mutex)
51 signal(full)
52 random_sleep()
56 func consumer () {
57 for { // laço infinito
58 wait(full)
59 wait(mutex)
60 v := buffer[front]
61 front = (front + 1) % BUFFER_SIZE
62 Println("\t\t\tconsuming:", v)
63 signal(mutex)
64 signal(empty)
65 random_sleep()
69 func main () {
70 buffer = make([]int, BUFFER_SIZE)
71 empty = make(chan int, BUFFER_SIZE);
72 full = make(chan int, BUFFER_SIZE)
73 for i := 0; i < BUFFER_SIZE; i++ { // inicializa empty com o valor BUFFER\_SIZE
74 signal(empty)
76 signal(mutex) // inicializa mutex com o valor 1
77 go producer()
78 go consumer()
79 wait(make(chan int)) // espera indefinidamente