分享
Go channel 实现自增长ID
yumuxu · · 13042 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
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/
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信13042 次点击
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
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/