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);
}
}
}
Aucun commentaire:
Enregistrer un commentaire