Skip to content

Commit 61bb81f

Browse files
committed
feat: add pthread race condition demonstration using shared variable
Implemented a multithreaded C program where two threads concurrently modify a shared global variable without synchronization. Demonstrates real-world data races and non-deterministic output caused by unsynchronized access to shared memory. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 4026d79 commit 61bb81f

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#include <pthread.h>
2+
#include <stdio.h>
3+
#include <stdlib.h>
4+
#include <unistd.h>
5+
6+
// Shared variable used by both threads
7+
volatile long int a = 0;
8+
9+
// Thread function 1 — increments 'a' by each loop index
10+
void* threadFunction1(void* args)
11+
{
12+
for (int i = 1; i <= 500000; i++) {
13+
a = a + i; // Updating shared variable (not thread-safe)
14+
}
15+
return NULL;
16+
}
17+
18+
// Thread function 2 — performs the same addition as thread 1
19+
void* threadFunction2(void* args)
20+
{
21+
for (int i = 1; i <= 500000; i++) {
22+
a = a + i; // Concurrent modification of shared data
23+
}
24+
return NULL;
25+
}
26+
27+
int main(int argc, char** argv)
28+
{
29+
pthread_t one, two; // Thread identifiers
30+
a = 0; // Initialize shared variable
31+
32+
// Start two threads running separate functions
33+
pthread_create(&one, NULL, threadFunction1, NULL);
34+
pthread_create(&two, NULL, threadFunction2, NULL);
35+
36+
// Wait for both threads to finish
37+
pthread_join(one, NULL);
38+
pthread_join(two, NULL);
39+
40+
// Print the final result after both threads have completed
41+
printf("Final value of a = %ld\n", a);
42+
43+
return 0;
44+
}
45+
46+
/*
47+
• Actually creates two threads with pthread_create.
48+
• Both threadFunction1 and threadFunction2 run concurrently, each modifying the same global variable a.
49+
• Because updates to a are not synchronized, the final result varies each run — a textbook race condition example.
50+
• Demonstrates real multithreading behavior.
51+
52+
Result: inconsistent and unpredictable — shows concurrency and data races.
53+
*/

0 commit comments

Comments
 (0)