Last active
May 13, 2021 03:39
-
-
Save youknowcast/f797c4ab3af63195ced69fcf07551684 to your computer and use it in GitHub Desktop.
To use golang Mutex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
はい,テスト用に時間を注入できるようにしていますが,ここでは使ってないですね・・