The Go Programming Language

Source file doc/progs/server1.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, quit chan bool) {
    22		for {
    23			select {
    24			case req := <-service:
    25				go run(op, req) // don't wait for it
    26			case <-quit:
    27				return
    28			}
    29		}
    30	}
    31	
    32	func startServer(op binOp) (service chan *request, quit chan bool) {
    33		service = make(chan *request)
    34		quit = make(chan bool)
    35		go server(op, service, quit)
    36		return service, quit
    37	}
    38	
    39	func main() {
    40		adder, quit := startServer(func(a, b int) int { return a + b })
    41		const N = 100
    42		var reqs [N]request
    43		for i := 0; i < N; i++ {
    44			req := &reqs[i]
    45			req.a = i
    46			req.b = i + N
    47			req.replyc = make(chan int)
    48			adder <- req
    49		}
    50		for i := N - 1; i >= 0; i-- { // doesn't matter what order
    51			if <-reqs[i].replyc != N+2*i {
    52				fmt.Println("fail at", i)
    53			}
    54		}
    55		quit <- true
    56	}

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