Skip to content

Fix worker id conflict in generator test #47

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 28, 2022

Conversation

itchyny
Copy link
Contributor

@itchyny itchyny commented Jan 23, 2022

I noticed that worker id generator in a test (getNextWorkerID) can return duplicate ids.

For proof, run the following code for multiple times.

main.go
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

var nextWorkerID uint32

func getNextWorkerID() uint {
	atomic.AddUint32(&nextWorkerID, 1)
	return uint(nextWorkerID)
}

const total = 500

func main() {
	var wg sync.WaitGroup
	var m sync.Map
	for i := 0; i < total; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			id := getNextWorkerID()
			if _, loaded := m.LoadOrStore(id, 0); loaded {
				fmt.Printf("conflict: %d\n", id)
			}
		}()
	}
	wg.Wait()
	var cnt int
	m.Range(func(_, _ interface{}) bool { cnt++; return true })
	if cnt != total {
		fmt.Printf("map size: %d != %d\n", cnt, total)
	}
}
 $ for i in `seq 100`; do go run main.go; done
conflict: 454
map size: 499 != 500
conflict: 470
map size: 499 != 500
conflict: 181
map size: 499 != 500

@fujiwara fujiwara merged commit fc1ba57 into kayac:master Jan 28, 2022
@fujiwara
Copy link
Collaborator

Great! Thank you!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants