Skip to content

Commit e46dcf3

Browse files
Create transactions.c
1 parent f573b89 commit e46dcf3

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

transactions.c

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
Handles simple transactions and avoids race conditions
3+
with the help of mutexes when interacting with critical regions
4+
*/
5+
6+
7+
#include <stdio.h>
8+
#include <stdlib.h>
9+
#include <pthread.h>
10+
11+
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
12+
double bankAccountBalance = 0;
13+
bool lock = 1;
14+
15+
void deposit(double amount) {
16+
pthread_mutex_lock(&lock);
17+
bankAccountBalance += amount;
18+
pthread_mutex_unlock(&lock);
19+
}
20+
21+
void withdraw(double amount) {
22+
pthread_mutex_lock(&lock);
23+
bankAccountBalance -= amount;
24+
pthread_mutex_unlock(&lock);
25+
}
26+
27+
unsigned odd(unsigned long num) {
28+
return num % 2;
29+
}
30+
31+
void do1000Transactions(unsigned long id) {
32+
for (int i = 0; i < 1000; i++) {
33+
if (odd(id))
34+
deposit(100.00);
35+
else
36+
withdraw(100.00);
37+
}
38+
}
39+
40+
void* child(void* buf) {
41+
unsigned long childID = (unsigned long)buf;
42+
do1000Transactions(childID);
43+
return NULL;
44+
}
45+
46+
int main(int argc, char** argv) {
47+
pthread_t *children;
48+
unsigned long id = 0;
49+
unsigned long nThreads = 0;
50+
if (argc > 1)
51+
nThreads = atoi(argv[1]);
52+
children = malloc( nThreads * sizeof(pthread_t) );
53+
for (id = 1; id < nThreads; id++)
54+
pthread_create(&(children[id-1]), NULL, child, (void*)id);
55+
do1000Transactions(0); // main thread work (id=0)
56+
for (id = 1; id < nThreads; id++)
57+
pthread_join(children[id-1], NULL);
58+
printf("\nThe final account balance with %lu threads is $%.2f.\n\n", nThreads, bankAccountBalance);
59+
free(children);
60+
pthread_mutex_destroy(&lock);
61+
return 0;
62+
}

0 commit comments

Comments
 (0)