Skip to content

Instantly share code, notes, and snippets.

@youknowcast
Last active May 13, 2021 03:39
Show Gist options
  • Save youknowcast/f797c4ab3af63195ced69fcf07551684 to your computer and use it in GitHub Desktop.
Save youknowcast/f797c4ab3af63195ced69fcf07551684 to your computer and use it in GitHub Desktop.
To use golang Mutex
package main
import (
"fmt"
"sync"
)
func main() {
InitUlidGenerator(nil)
var wg sync.WaitGroup
fn := func(idx int) {
id := GenUlid()
fmt.Println(id)
defer wg.Done()
}
for i := 0; i < 100; i++ {
wg.Add(1)
idx := i
go fn(idx)
}
wg.Wait()
}
package main
import (
"io"
"math/rand"
"sync"
"time"
"github.com/oklog/ulid"
)
type Ulid struct {
mu sync.Mutex
t time.Time
entropy io.Reader
}
var ulidGen *Ulid
func InitUlidGenerator(now func() time.Time) {
var currentTime time.Time
if now != nil {
currentTime = now()
} else {
currentTime = time.Now()
}
ulidGen = new(Ulid)
ulidGen.t = time.Unix(currentTime.Unix(), 0)
ulidGen.entropy = ulid.Monotonic(rand.New(rand.NewSource(ulidGen.t.UnixNano())), 0)
}
// genUlid generates ULID.
// see: https://qiita.com/kai_kou/items/b4ac2d316920e08ac75a
func GenUlid() string {
if ulidGen == nil {
InitUlidGenerator(nil)
}
ulidGen.mu.Lock()
defer ulidGen.mu.Unlock()
id := ulid.MustNew(ulid.Timestamp(ulidGen.t), ulidGen.entropy).String()
return id
}
@youknowcast
Copy link
Author

はい,テスト用に時間を注入できるようにしていますが,ここでは使ってないですね・・

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment