The Go Programming Language

Source file doc/progs/server.go

     1	// Copyright 2009 The Go Authors. All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	package main
     6	
     7	import "fmt"
     8	
     9	type request struct {
    10		a, b   int
    11		replyc chan int
    12	}
    13	
    14	type binOp func(a, b int) int
    15	
    16	func run(op binOp, req *request) {
    17		reply := op(req.a, req.b)
    18		req.replyc <- reply
    19	}
    20	
    21	func server(op binOp, service chan *request) {
    22		for {
    23			req := <-service
    24			go run(op, req) // don't wait for it
    25		}
    26	}
    27	
    28	func startServer(op binOp) chan *request {
    29		req := make(chan *request)
    30		go server(op, req)
    31		return req
    32	}
    33	
    34	func main() {
    35		adder := startServer(func(a, b int) int { return a + b })
    36		const N = 100
    37		var reqs [N]request
    38		for i := 0; i < N; i++ {
    39			req := &reqs[i]
    40			req.a = i
    41			req.b = i + N
    42			req.replyc = make(chan int)
    43			adder <- req
    44		}
    45		for i := N - 1; i >= 0; i-- { // doesn't matter what order
    46			if <-reqs[i].replyc != N+2*i {
    47				fmt.Println("fail at", i)
    48			}
    49		}
    50		fmt.Println("done")
    51	}

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.