之前在做唯一性id创建的时候,想依赖时间戳,本想着time.Now().UnixNano()应该是唯一的,但是!!!在高并发下真的不会发生问题吗!!!!!!!!!!!!!!!!!!!!!!!!!!来一起走进科学。

package main

import (
    "time"
    "runtime"
    "github.com/fwhezfwhez/go-queue"
    "strconv"
    "fmt"
    "sync"
)
var mutex sync.Mutex

func init() {
    fmt.Print(time.Now().UnixNano())
}
func main() {
    runtime.GOMAXPROCS(runtime.NumCPU())
    wg :=sync.WaitGroup{}


    var queue = Queue.NewEmpty()
    //var rs = make([]int64,0)
    for i:=0;i<5000;i++ {
        wg.Add(1)
        go func(in int,q *Queue.Queue){
            tmp:= getNum()
            //add(&rs, tmp)
            q.SafePush(tmp)
            fmt.Println("finish "+strconv.Itoa(in)+",produce:"+strconv.FormatInt(tmp,10))
            wg.Done()
        }(i,queue)
    }
    wg.Wait()
    queue.Print()
    fmt.Print(queue.ValidLength())
    //fmt.Println(rs)
    //fmt.Println(len(rs))
}

func getNum()int64{
    mutex.Lock()
    defer mutex.Unlock()
    return time.Now().UnixNano()
}
func add(rs *[]int64,i int64){
    mutex.Lock()
    defer mutex.Unlock()
    *rs = append(*rs,i)
}

结果显然违反了唯一性约束!!!!!
这里写图片描述