Go channel 实现自增长ID

 1 //autoInc.go
 2 
 3 package autoInc
 4 
 5 type AutoInc struct {
 6     start, step int
 7     queue       chan int
 8     running     bool
 9 }
10 
11 func New(start, step int) (ai *AutoInc) {
12     ai = &AutoInc{
13         start:   start,
14         step:    step,
15         running: true,
16         queue:   make(chan int, 4),
17     }
18 
19     go ai.process()
20     return
21 }
22 
23 func (ai *AutoInc) process() {
24     defer func() { recover() }()
25     for i := ai.start; ai.running; i = i + ai.step {
26         ai.queue <- i
27     }
28 }
29 
30 func (ai *AutoInc) Id() int {
31     return <-ai.queue
32 }
33 
34 func (ai *AutoInc) Close() {
35     ai.running = false
36     close(ai.queue)
37 }

转自:http://mikespook.com/2012/06/golang-channel-%E6%9C%89%E8%B6%A3%E7%9A%84%E5%BA%94%E7%94%A8/

posted @ 2014-10-31 10:32  yumuxu  阅读(691)  评论(0编辑  收藏  举报