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

What's mean "move the keys and values in memory" ? #14

Closed
mlkt opened this issue Jun 12, 2019 · 6 comments
Closed

What's mean "move the keys and values in memory" ? #14

mlkt opened this issue Jun 12, 2019 · 6 comments

Comments

@mlkt
Copy link

mlkt commented Jun 12, 2019

The flat hash maps may move the keys and values in memory. So if you keep a pointer to something inside a flat hash map, this pointer may become invalid when the map is mutated. The node hash maps don't, and should be used instead if this is a problem.

What's mean "move the keys and values in memory" ?
Why "pointer may become invalid"?I can't understand.

Because used memcpy() and didn't use the copy constructor?

@greg7mdp
Copy link
Owner

Hi @mlkt,

Suppose you have this class:

struct A {
    int x;
    int y;
};

and a map phmap::flat_hash_map<int, A> map;.

Now you insert values into the map:

map[1] = A{22,34};
map[2] = A{38,99};
map[3] = A{85,65};

What is dangerous is to store a pointer to a value inside the flat_hash_map, as in:

int *p = &map[2].x;
printf("%d\n", *p); // => prints 38

When new values are inserted into the phmap, the value pointed by p is likely to change:

map[4] = A{4,5};
map[5] = A{6,7};
printf("%d\n", *p); // => prints -572662307

Hope this helps!

@mlkt
Copy link
Author

mlkt commented Jun 12, 2019

OK, thanks, I see. If so, in a multithreaded environment, after getting a value's reference, the reference may become invalid before read it ? (even if mutex are used)

@greg7mdp
Copy link
Owner

greg7mdp commented Jun 12, 2019

in a multithreaded environment, after getting a value's reference, the reference may become invalid before read it ? (even if mutex are used)

yes, unfortunately, you can't rely on internal mutexes for this.

@mlkt
Copy link
Author

mlkt commented Jun 13, 2019

so in this case, use parallel_node_hash_map ?

@greg7mdp
Copy link
Owner

parallel_node_hash_map should be OK for a value reference (unless it is deleted from another thread of course), but iterators would not work reliably.

@mlkt
Copy link
Author

mlkt commented Jun 14, 2019

OK, Thanks!

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

No branches or pull requests

2 participants