0

The problem statement:

I have one content type called 'Employee' which has 10 nodes. I have to perform the voting for each node. I am saving the vote count in the field called 'vote count'.

But when I met the below scenario I have an issue of updating vote count for a single employee.

Scenario: 20 people voting for one employee at a time. This means the node will save the 20 times for updating the vote count. This may lead to race_condition while saving the node. But vote count is not updating correctly. This m=is due to race_condition?

I am using the lock_aquire() and lock_release() in below code.

is it right way to use this two functions while saving same node multiple times? or any other way to update the count?

I have tried below attempt so far:

  1. added ajax call back in js
jQuery.ajax({
        type: 'POST',
        url: '/ajax/vote',
        dataType: 'json',
        data: {"nid": nid},
         success: function(response){}
});
  1. menu hook with path :

/ajax/vote

  1. A page call back function general_voting_update_vote to save the node;
function general_voting_update_vote() {
          $lock_name = 'register_vote';
          $nodeId = !empty($_POST['nid']) ? $_POST['nid'] : '';
          $node = node_load($nodeId);
          $vote = $node->field_vote_count_submitted[$node->language][0]['value'] + 1;
          $node->field_vote_count_submitted[$node->language][0]['value'] = $vote;
          $lock_acquired = lock_acquire($lock_name, 5.0);
          if (!empty($lock_acquired)) { 
            node_save($node);
          }
          lock_release($lock_name);
}
2
  • 1
    You may want to consider taking a different approach - like for example saving the individual votes somewhere separate when they happen (database, file system, whatever), then having a scheduled job to update the node based on that separate storage. That way you avoid the race condition, not to mention the large number of more expensive node save ops you will avoid – Clive Jul 31 '20 at 12:53
  • is it good to use lock_aquire() and lock_release() ? – Rohan1990 Jul 31 '20 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.