Skip to content
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

Will it cause new keys can't been set when deleting keys in ForEach iteration? #14

Closed
bagualing opened this issue Sep 25, 2022 · 4 comments
Labels
bug Something isn't working

Comments

@bagualing
Copy link

bagualing commented Sep 25, 2022

Code:

package main

import (
	"context"
	"fmt"
	"math/rand"
	"time"

	"github.com/alphadose/haxmap"
)

type data struct {
	id  int
	exp time.Time
}

func main() {
	c := haxmap.New[int, *data](256)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	go func() {
		t := time.NewTicker(time.Second * 2)
		defer t.Stop()
		var count int
		for {
			select {
			case <-t.C:
				count = 0
				c.ForEach(func(s int, b *data) bool {
					if time.Now().After(b.exp) {
						c.Del(s)
						count++
					}
					return true
				})
				fmt.Println("Del", count)
			case <-ctx.Done():
				return
			}
		}
	}()

	for i := 0; i < 20000; i++ {
		c.Set(i, &data{id: i, exp: time.Now().Add(time.Millisecond * time.Duration((1000 + rand.Intn(800))))})
		time.Sleep(time.Microsecond * time.Duration(rand.Intn(200)+10))
		if i%100 == 0 {
			fmt.Println(i)
		}
	}

	time.Sleep(time.Second * 3)
	fmt.Println("LEN", c.Len())
}

Running the above code, setting the new Key will stop.

@alphadose
Copy link
Owner

@bagualing which version of haxmap are you using ?

@bagualing
Copy link
Author

@bagualing which version of haxmap are you using ?

haxmap v1.0.0 & go v1.19.1

@alphadose alphadose added the bug Something isn't working label Sep 26, 2022
@alphadose
Copy link
Owner

@bagualing this issue is fixed in https://github.com/alphadose/haxmap/releases/tag/v1.0.1

the snippet you provided above is now working

I encourage you to test this yourself

Also many thanks for pointing this out :)

@bagualing
Copy link
Author

@alphadose Oh, that's great! Thanks for your excellent work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants