1 // $G $D/$F.go && $L $F.$A && ./$A.out
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 // Test close(c), closed(c).
9 // TODO(rsc): Doesn't check behavior of close(c) when there
10 // are blocked senders/receivers.
24 // direct channel operations
26 func (c XChan) Send(x int) {
30 func (c XChan) Nbsend(x int) bool {
34 func (c XChan) Recv() int {
38 func (c XChan) Nbrecv() (int, bool) {
43 func (c XChan) Close() {
47 func (c XChan) Closed() bool {
51 func (c XChan) Impl() string {
52 return "(<- operator)"
55 // indirect operations via select
57 func (c SChan) Send(x int) {
63 func (c SChan) Nbsend(x int) bool {
73 func (c SChan) Recv() int {
81 func (c SChan) Nbrecv() (int, bool) {
91 func (c SChan) Close() {
95 func (c SChan) Closed() bool {
99 func (c SChan) Impl() string {
104 // not closed until the close signal (a zero value) has been received.
106 println("test1: Closed before Recv zero:", c.Impl())
109 for i := 0; i < 3; i++ {
110 // recv a close signal (a zero value)
111 if x := c.Recv(); x != 0 {
112 println("test1: recv on closed got non-zero:", x, c.Impl())
115 // should now be closed.
117 println("test1: not closed after recv zero", c.Impl())
120 // should work with ,ok: received a value without blocking, so ok == true.
123 println("test1: recv on closed got not ok", c.Impl())
126 println("test1: recv ,ok on closed got non-zero:", x, c.Impl())
130 // send should work with ,ok too: sent a value without blocking, so ok == true.
133 println("test1: send on closed got not ok", c.Impl())
136 // but the value should have been discarded.
137 if x := c.Recv(); x != 0 {
138 println("test1: recv on closed got non-zero after send on closed:", x, c.Impl())
143 if x := c.Recv(); x != 0 {
144 println("test1: recv on closed got non-zero after send on closed:", x, c.Impl())
148 func testasync1(c Chan) {
149 // not closed until the close signal (a zero value) has been received.
151 println("testasync1: Closed before Recv zero:", c.Impl())
154 // should be able to get the last value via Recv
155 if x := c.Recv(); x != 1 {
156 println("testasync1: Recv did not get 1:", x, c.Impl())
162 func testasync2(c Chan) {
163 // not closed until the close signal (a zero value) has been received.
165 println("testasync2: Closed before Recv zero:", c.Impl())
168 // should be able to get the last value via Nbrecv
169 if x, ok := c.Nbrecv(); !ok || x != 1 {
170 println("testasync2: Nbrecv did not get 1, true:", x, ok, c.Impl())
176 func closedsync() chan int {
182 func closedasync() chan int {
183 c := make(chan int, 2)
190 test1(XChan(closedsync()))
191 test1(SChan(closedsync()))
193 testasync1(XChan(closedasync()))
194 testasync1(SChan(closedasync()))
195 testasync2(XChan(closedasync()))
196 testasync2(SChan(closedasync()))