Search code examples
crandommodulo

What does `rand() % 2` mean?


I've come across this program but I can't seem to figure out this part. Please help me understand what is the use of rand() % 2 and how is it a condition to determine whether it's credit or debit?

#include<stdio.h>
#define NUM_TRANS 400
void * transactions(void * args) {
  int v;
    
  for(int i = 0; i < NUM_TRANS; i++) {
    v = (int) rand() % NUM_TRANS;
  
    if (rand() % 2) {
      // Crediting to user
      
     
      pthread_mutex_lock(&balance_lock);
      balance = balance + v;
      pthread_mutex_unlock(&balance_lock);
      
      pthread_mutex_lock(&credits_lock);
      credits = credits + v;
      pthread_mutex_unlock(&credits_lock);
      
    } else {
      // Debiting from user

      pthread_mutex_lock(&balance_lock);
      balance = balance - v;
      pthread_mutex_unlock(&balance_lock);
      
      pthread_mutex_lock(&debits_lock);
      debits = debits + v;
      pthread_mutex_unlock(&debits_lock);
    }
  }
}

Solution

  • The rand() % 2 is a way of generating a pseudo-random number that's either 0 or 1.

    The rand() function generates a pseudo-random integer. When you take the modulus of that integer by 2 (i.e., rand() % 2), you're essentially asking for the remainder of the division of the random number by 2.

    Since any number divided by 2 has a remainder of either 0 or 1, rand() % 2 will always result in either 0 or 1. This is equivalent to flipping a coin where there are only two possible outcomes.

    In this program, rand() % 2 is used in an if condition to randomly decide between two different operations:

    If rand() % 2 evaluates to 1 (or any non-zero number, which is considered true in C), then the program credits a user with a pseudo-random value v.

    If rand() % 2 evaluates to 0 (which is considered false in C), then the program debits a user with the pseudo-random value v.

    The use of a mutex lock around these operations is to ensure that no other thread can access and modify the balance, credits, and debits variables at the same time, avoiding race conditions in a multithreaded context.