Skip to content

The NewID interface may encounter lock contention issues during high concurrency #479

@xiaohui-txh

Description

@xiaohui-txh

When I call NewKnowledgeBaseInstance every time I call Execute, there is a lock contention issue with 100 concurrent calls

The source code is as follows:
package unique

import (
"fmt"
"sync"
"time"
)

var (
offset int64 = 0
lastMS int64 = 0
mutex sync.Mutex
)

// NewID will create a new unique ID string for this runtime.
// Uniqueness between system or apps is not necessary.
func NewID() string {
mutex.Lock()
defer mutex.Unlock()
millisUnix := time.Now().Unix()
if lastMS == millisUnix {
offset++

	return fmt.Sprintf("%d-%d", lastMS, offset)
}
lastMS = millisUnix
offset = 0

return fmt.Sprintf("%d-%d", lastMS, offset)

}

Suggest using atomic variables

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions