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

Is ConcurrentHashMap read lock-free? #2103

Open
NoWarnNoError opened this issue Nov 28, 2023 · 2 comments
Open

Is ConcurrentHashMap read lock-free? #2103

NoWarnNoError opened this issue Nov 28, 2023 · 2 comments

Comments

@NoWarnNoError
Copy link

NoWarnNoError commented Nov 28, 2023

when I read the ConcurrentHashMap implementation, the ConcurrentHashMap's operator[] will finally call
"ensureSegment(segment)->insert(res.first.it, h, std::move(foo));_", which uses BucketTable's doInsert function. And at the function begining, has a unique_lock. So I think ConcurrentHashMap's read is not lock-free. Do I get mistake on this question?

@NoWarnNoError NoWarnNoError changed the title Is ConcurrentHashMap Is ConcurrentHashMap read lock-free? Nov 28, 2023
@instw
Copy link

instw commented Dec 1, 2023

Technically ConcurrentHashMap reads are indeed lock-free (and wait-free). An operation like find() will does not need to lock a bucket.

However the operator[] is not a read-only operation. Similar to a regular std::unordered_map, doing a auto& value = map[5]; when 5 doesn't exist would result in creating an entry for key = 5 with default constructing it's value, and then returning a reference to that value. This is a write-oriented operation, and hence is NOT lock-free.

An alternative would be to use map.at(5) which is indeed lock-free. Most (all?) const member functions of ConcurrentHashMap are lock-free

@NoWarnNoError
Copy link
Author

Technically ConcurrentHashMap reads are indeed lock-free (and wait-free). An operation like find() will does not need to lock a bucket.

However the operator[] is not a read-only operation. Similar to a regular std::unordered_map, doing a auto& value = map[5]; when 5 doesn't exist would result in creating an entry for key = 5 with default constructing it's value, and then returning a reference to that value. This is a write-oriented operation, and hence is NOT lock-free.

An alternative would be to use map.at(5) which is indeed lock-free. Most (all?) const member functions of ConcurrentHashMap are lock-free

Thanks your reply, I also read the code find the answer. Issuing this question verifies my thought. 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