1

In a popular sale contract, what would happen if the following code was true?

totalNumberOfTokensDistributed = 0;
totalNumberOfTokensAvailable = 100;

function claimTokens() {
    uint tempTotalCollected = totalNumberOfTokensDistributed + 2;
    require(tempTotalCollected <= totalNumberOfTokensAvailable);

    totalNumberOfTokensDistributed = tempBeingCollected
    // Address that calls function gets 2 tokens
}

The function allows the creator the check if the function call will not be over than the total number available. If two or more users were to call this function in the same block, how would totalNumberOfTokensDistributed = tempBeingCollected behave? If 4 users called this function in one block, would totalNumberOfTokensDistributed be 8? Or would it be overwritten by every use and only end at 2?

I know a solution is totalNumberOfTokensDistributed += 2;, but I am curious about race conditions in Solidity.

3

Contract executions are serialised within a block, they are not performed in parallel, so there is no race condition here. Everything will behave as if the transactions had been included in separate blocks.

Note that the miners decide in what order to include transactions in a block, so there is a degree of non-determinism, but that's a different issue.

  • Could you give a reference for this? – ferit Aug 26 '18 at 7:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.