Reputation: 103
// created a copy of CNode and added the new value
CNode *copyCNode = new CNode;
//memcpy(c, iNode->mainNode->cNode, sizeof(*(iNode->mainNode->cNode)) );
memcpy(copyCNode, iNode->mainNode->cNode, sizeof(CNode) );
CNode *updated_cnode = inserted(copyCNode, b, index);
std::cout << "temporay CNode created : " << updated_cnode->branch[index]->sNode->value << std::endl;
if(memcmp(copyCNode, iNode->mainNode->cNode, sizeof(CNode)) == 0){
std::cout << "mainNode is not changed " << std::endl ;
}else{
std::cout << "mainNode is changed" << std::endl;
}
bool cas_ret = __sync_bool_compare_and_swap(&iNode->mainNode->cNode, copyCNode, updated_cnode);
std::cout << "return cas_ret : " << cas_ret << std::endl;
if(cas_ret){
std::cout << "New added value " << iNode->mainNode->cNode->branch[index]->sNode->value << std::endl;
return 0; // successfully attached the node
}
else{
return 1;
}
The above code is part of my code base. There is no compilation error and the code is running fine. But __sync_bool_compare_and_swap function always return false in my code. Even before the CAS function call I did the memory comparison (memcpy) and its showing that both the arguments are equal, in that case CAS should swap the value with third argument, but it is not.
copyCNode -> Holds the copy value of iNode->mainNode->cNode
updated_cnode -> Holds the updated value of iNode->mainNode->cNode (New branch added)
Please suggest any solution. Thanks
Upvotes: 1
Views: 562
Reputation: 103
I got the solution.
I think I should not create the memory for copyNode. Instead, I should just copyNode = iNode->mainNode->cNode
and the rest code is working good.
Thanks @jxh
Upvotes: 0
Reputation: 70402
The CAS operation failed because: iNode->mainNode->cNode
≠ copyCNode
. It doesn't matter that their contents are both the same. The CAS operation is trying to do:
if (iNode->mainNode->cNode == copyCNode) {
iNode->mainNode->cNode = updated_cnode;
return true;
}
return false;
All you verified is that *copyCnode
= *iNode->mainNode->cNode
, which is not what the CAS operation is interested in.
Upvotes: 1