@kjk1/

gobook channels buffered

Go

No description

fork
loading
Files
  • main.go

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.421742582180342","path":"main.go","file":{"path":"main.go","content":{"asEncoding":{"base64":"cGFja2FnZSBtYWluCgppbXBvcnQgKAoJImZtdCIKCSJ0aW1lIgopCgovLyA6c2hvdyBzdGFydAoKZnVuYyBwcm9kdWNlcihjaCBjaGFuIGludCkgewoJZm9yIGkgOj0gMDsgaSA8IDU7IGkrKyB7CgkJaWYgaSUyID09IDAgewoJCQl0aW1lLlNsZWVwKDEwICogdGltZS5NaWxsaXNlY29uZCkKCQl9IGVsc2UgewoJCQl0aW1lLlNsZWVwKDEgKiB0aW1lLk1pbGxpc2Vjb25kKQoJCX0KCQljaCA8LSBpCgl9Cn0KCmZ1bmMgY29uc3VtZXIoY2ggY2hhbiBpbnQpIHsKCXRvdGFsIDo9IDAKCWZvciBpIDo9IDA7IGkgPCA1OyBpKysgewoJCWlmIGklMiA9PSAxIHsKCQkJdGltZS5TbGVlcCgxMCAqIHRpbWUuTWlsbGlzZWNvbmQpCgkJfSBlbHNlIHsKCQkJdGltZS5TbGVlcCgxICogdGltZS5NaWxsaXNlY29uZCkKCQl9CgkJdG90YWwgKz0gPC1jaAoJfQp9CgpmdW5jIHVuYnVmZmVyZWQoKSB7Cgl0aW1lU3RhcnQgOj0gdGltZS5Ob3coKQoJY2ggOj0gbWFrZShjaGFuIGludCkKCWdvIHByb2R1Y2VyKGNoKQoJY29uc3VtZXIoY2gpCglmbXQuUHJpbnRmKCJVbmJ1ZmZlcmVkIHZlcnNpb24gdG9vayAlc1xuIiwgdGltZS5TaW5jZSh0aW1lU3RhcnQpKQp9CgpmdW5jIGJ1ZmZlcmVkKCkgewoJdGltZVN0YXJ0IDo9IHRpbWUuTm93KCkKCWNoIDo9IG1ha2UoY2hhbiBpbnQsIDUpCglnbyBwcm9kdWNlcihjaCkKCWNvbnN1bWVyKGNoKQoJZm10LlByaW50ZigiQnVmZmVyZWQgdmVyc2lvbiB0b29rICVzXG4iLCB0aW1lLlNpbmNlKHRpbWVTdGFydCkpCn0KCmZ1bmMgbWFpbigpIHsKCXVuYnVmZmVyZWQoKQoJYnVmZmVyZWQoKQp9CgovLyA6c2hvdyBlbmQ="},"asBuffer":null},"loaded":true}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main

import (
	"fmt"
	"time"
)

// :show start

func producer(ch chan int) {
	for i := 0; i < 5; i++ {
		if i%2 == 0 {
			time.Sleep(10 * time.Millisecond)
		} else {
			time.Sleep(1 * time.Millisecond)
		}
		ch <- i
	}
}

func consumer(ch chan int) {
	total := 0
	for i := 0; i < 5; i++ {
		if i%2 == 1 {
			time.Sleep(10 * time.Millisecond)
		} else {
			time.Sleep(1 * time.Millisecond)
		}
		total += <-ch
	}
}

func unbuffered() {
	timeStart := time.Now()
	ch := make(chan int)
	go producer(ch)
	consumer(ch)
	fmt.Printf("Unbuffered version took %s\n", time.Since(timeStart))
}

func buffered() {
	timeStart := time.Now()
	ch := make(chan int, 5)
	go producer(ch)
	consumer(ch)
	fmt.Printf("Buffered version took %s\n", time.Since(timeStart))
}

func main() {
	unbuffered()
	buffered()
}

// :show end