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

Listing 7.3 - add early exit to .pop() #36

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

ITHelpDec
Copy link

@ITHelpDec ITHelpDec commented May 31, 2023

It seems odd to perform work on a node that could potentially be a nullptr from the moment the function is called.

I hope I'm correct in saying that .compare_exchange_weak(...) will return true if head still refers to our original old_head (i.e. no other thread has had a chance to modify it), but if that old_head was nullptr to begin with, then would old_head->next not throw after a successful CAS check?

std::shared_ptr<T> pop()
{
if (!head_) { return std::shared_ptr<T>(); }
node* old_head=head.load();
while(!head.compare_exchange_weak(old_head,old_head->next));
return old_head->data;
}


The same thing applies to void pop(T &val) a few pages prior - an early exit allows the code the run without throwing for bad access to old_head->next.


Arguably, maybe changing old_head to original_head would be more conducive to helping readers grasp the concept of .compare_exchange_weak(...).

ITHelpDec added 2 commits May 31, 2023 16:19
- seems odd to perform work on a node that could potentially be a nullptr from the moment the function is called (regardless of CAS)
- same thing applies to `void pop(T &val)` (early exit allows the code the run without throwing for bad access to `old_head->next`)
- optional, but maybe more useful in understanding the intent of `.compare_exchange_weak(...)`
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.

1 participant