Go - Generators
Updated at 2013-11-11 23:37
Thread safe unique ID generator.
package main
import "fmt"
func getIdGenerator() chan string {
c := make(chan string)
go func() {
var nextId int64 = 0
for {
c <- fmt.Sprintf("%x", nextId)
nextId += 1
}
}()
return c
}
func main() {
idGenerator1 := getIdGenerator()
fmt.Println(<-idGenerator1) // 0
fmt.Println(<-idGenerator1) // 1
fmt.Println(<-idGenerator1) // 2
idGenerator2 := getIdGenerator()
idGenerator3 := getIdGenerator()
fmt.Println(<-idGenerator1) // 3
fmt.Println(<-idGenerator2) // 0
fmt.Println(<-idGenerator3) // 0
}