There exists an array of objects that is being expanded through parallel ajax requests. Once the last request is complete, the array needs to be processed. One possible solution can be seen below:
function expandArray(objects, callback){
number_of_requests = objects.length - 1;
for(i in objects){
$.getJSON(request, function(){
//expanding array
if(--number_of_requests == 0){
callback();
}
});
}
}
However, since the requests are executed in parallel, there is a possibility of a race condition occurring. The variable number_of_requests may be modified by two "threads" simultaneously. How can we prevent this chance of a race condition?