| 1 | import time |
| 2 | |
| 3 | fn do_rec(ch chan int, resch chan i64) { |
| 4 | mut sum := i64(0) |
| 5 | for { |
| 6 | a := <-ch or { break } |
| 7 | sum += a |
| 8 | } |
| 9 | assert ch.closed == true |
| 10 | println(sum) |
| 11 | resch <- sum |
| 12 | } |
| 13 | |
| 14 | fn do_send(ch chan int) { |
| 15 | for i in 0 .. 8000 { |
| 16 | ch <- i |
| 17 | } |
| 18 | assert ch.closed == false |
| 19 | ch.close() |
| 20 | assert ch.closed == true |
| 21 | } |
| 22 | |
| 23 | fn test_channel_close_buffered_multi() { |
| 24 | ch := chan int{cap: 10} |
| 25 | resch := chan i64{} |
| 26 | spawn do_rec(ch, resch) |
| 27 | spawn do_rec(ch, resch) |
| 28 | spawn do_rec(ch, resch) |
| 29 | spawn do_rec(ch, resch) |
| 30 | spawn do_send(ch) |
| 31 | mut sum := i64(0) |
| 32 | for _ in 0 .. 4 { |
| 33 | sum += <-resch |
| 34 | } |
| 35 | assert sum == i64(8000) * (8000 - 1) / 2 |
| 36 | } |
| 37 | |
| 38 | fn test_channel_close_unbuffered_multi() { |
| 39 | ch := chan int{} |
| 40 | resch := chan i64{} |
| 41 | spawn do_rec(ch, resch) |
| 42 | spawn do_rec(ch, resch) |
| 43 | spawn do_rec(ch, resch) |
| 44 | spawn do_rec(ch, resch) |
| 45 | spawn do_send(ch) |
| 46 | mut sum := i64(0) |
| 47 | for _ in 0 .. 4 { |
| 48 | sum += <-resch |
| 49 | } |
| 50 | assert sum == i64(8000) * (8000 - 1) / 2 |
| 51 | } |
| 52 | |
| 53 | fn test_channel_close_buffered() { |
| 54 | ch := chan int{cap: 100} |
| 55 | resch := chan i64{} |
| 56 | spawn do_rec(ch, resch) |
| 57 | spawn do_send(ch) |
| 58 | mut sum := i64(0) |
| 59 | sum += <-resch |
| 60 | assert sum == i64(8000) * (8000 - 1) / 2 |
| 61 | } |
| 62 | |
| 63 | fn test_channel_close_unbuffered() { |
| 64 | ch := chan int{} |
| 65 | resch := chan i64{cap: 100} |
| 66 | spawn do_rec(ch, resch) |
| 67 | spawn do_send(ch) |
| 68 | mut sum := i64(0) |
| 69 | sum += <-resch |
| 70 | assert sum == i64(8000) * (8000 - 1) / 2 |
| 71 | } |
| 72 | |
| 73 | fn test_channel_send_close_buffered() { |
| 74 | ch := chan int{cap: 1} |
| 75 | t := spawn fn (ch chan int) { |
| 76 | ch <- 31 |
| 77 | mut x := 45 |
| 78 | ch <- 17 or { x = -133 } |
| 79 | |
| 80 | assert x == -133 |
| 81 | }(ch) |
| 82 | time.sleep(100 * time.millisecond) |
| 83 | ch.close() |
| 84 | mut r := <-ch |
| 85 | r = <-ch or { 23 } |
| 86 | assert r == 23 |
| 87 | t.wait() |
| 88 | } |
| 89 | |
| 90 | fn test_channel_send_close_unbuffered() { |
| 91 | time.sleep(1 * time.second) |
| 92 | ch := chan int{} |
| 93 | t := spawn fn (ch chan int) { |
| 94 | mut x := 31 |
| 95 | ch <- 177 or { x = -71 } |
| 96 | |
| 97 | assert x == -71 |
| 98 | }(ch) |
| 99 | time.sleep(100 * time.millisecond) |
| 100 | ch.close() |
| 101 | r := <-ch or { 238 } |
| 102 | assert r == 238 |
| 103 | t.wait() |
| 104 | } |
| 105 | |