Skip to content

When multiple goroutine calls consume, mb.newShard(md) will be called multiple times. #9739

Closed
@luyuanx2

Description

@luyuanx2

Describe the bug

The problematic code is as shown below:
image

Steps to reproduce

Here is a simple code showing this bug:

package main

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

type multiShardBatcher struct {
	batchers sync.Map

	lock sync.Mutex
	size int
}
type shard struct {
}

func (mb *multiShardBatcher) newShard() *shard {
	b := &shard{}
	fmt.Println("new shard")
	time.Sleep(1 * time.Second)
	return b
}

func (mb *multiShardBatcher) consume(key string) *shard {

	b, ok := mb.batchers.Load(key)
	if !ok {
		mb.lock.Lock()
		b, _ = mb.batchers.LoadOrStore(key, mb.newShard())
		mb.lock.Unlock()
	}
	return b.(*shard)
}

func main() {

	mb := &multiShardBatcher{}

	group := sync.WaitGroup{}
	for i := 0; i < 10; i++ {
		group.Add(1)
		go func() {
			mb.consume("key")
			group.Done()
		}()
	}
	group.Wait()

}
image

What did you expect to see?

What did you see instead?

What version did you use?

What config did you use?

Environment

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions