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 {
28 func wait (channel
chan int) {
32 // tenta simular a atomicidade necessária para o bom funcionamento da variável de condição
33 func wait_cond (channel
chan int, mutex
*Mutex
) {
34 c
:= make(chan int) // canal síncrono
35 go waiter(channel
, c
) // tentativa de simular a atomicidade - não funciona!!!
37 wait(c
) // em vez de wait(channel)
41 // espera pelo canal in e então sinaliza no canal out
42 func waiter (in
, out
chan int) {
47 // envia assincronamente um valor qualquer para o canal channel
48 func trysignal (channel
chan int) {
61 front
, rear
, count
int
66 func newMonitor () *Monitor
{
69 make(chan int), // variável de condição
70 make(chan int), // variável de condição
71 make([]int, BUFFER_SIZE
),
75 func (m
*Monitor
) produce (i
int) {
77 for m
.count
== BUFFER_SIZE
{ // buffer cheio?
78 wait_cond(m
.empty
, m
.mutex
)
80 Println("producing:", i
)
82 m
.rear
= (m
.rear
+ 1) % BUFFER_SIZE
88 func (m
*Monitor
) consume () {
90 for m
.count
== 0 { // buffer vazio?
91 wait_cond(m
.full
, m
.mutex
)
93 v
:= m
.buffer
[m
.front
]
94 m
.front
= (m
.front
+ 1) % BUFFER_SIZE
96 Println("\t\t\tconsuming:", v
)
102 for i
:= 0; ; i
++ { // laço infinito
109 for { // laço infinito
116 monitor
= newMonitor()
119 wait(make(chan int)) // espera indefinidamente