Disadvantages of using a reference parameter for the return value when pop () is blocked

I am currently reading Williams "C ++ Concurrency in Action". Now I settled on a topic dedicated to the implementation of lock-free pop ().

Without blocking:

void pop(T& result)
{
 node* old_head = head.load();
 while(!head.compare_exchange_weak(old_head,old_head->next));
 result=old_head->data;
}

Here is a quote from a discussion of this code:

The second problem is the security problem. . When we first introduced the thread-safe stack in Chapter 3, you saw how easy it is to return an object by value, leaving you with an exception safety problem: if an exception is thrown when copying the returned value, the value is lost. In this case, passing a reference to the result was an acceptable solution, because you could make sure that the stack was left unchanged if an exception was thrown. Unfortunately, here you do not have such luxury; you can safely copy the data as soon as you find out that the only thread returning the node, which means that the node is already removed from the queue. Therefore, passing to the target for the return value by reference is no longer an advantage: you can simply return the value. If you want to safely return a value, you should use another option from chapter 3: return a (smart) pointer to the data value

I do not understand how using a link can lead to problems with exceptions. I see the word “copy” here, but it cannot be used with links, “initialization”, “assignment”, but not “copy”. Therefore, I do not understand what is written after this "copy."

While searching on Google, I found Williams's explanation: https://forums.manning.com/posts/list/30887.page

but this does not clarify the question for me, because it again uses a “copy” with links:

"Normal" stack:

void pop(T& value)
{
 std::lock_guard<std::mutex> lock(m);
 if(data.empty()) throw empty_stack();
 value=data.top();
 data.pop();
}

"" , node , , node .

: ?

+4
1

result=old_head->data;, old_head->data -to result. , , . , , old_head->data result .

, "", , . , , , . "", , , .

+5

Source: https://habr.com/ru/post/1658016/


All Articles