Skip to content

Commit 210d97f

Browse files
committed
feat: add single-threaded baseline example for pthread comparison
Introduced a simple summation program without thread creation or synchronization. Serves as a deterministic baseline to compare against multithreaded versions that exhibit race conditions or mutex-based synchronization. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 61bb81f commit 210d97f

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <stdio.h>
2+
#include <pthread.h>
3+
#include <unistd.h>
4+
5+
// Shared global variable accessed by all threads
6+
volatile long int a = 0;
7+
8+
// Thread function 1 — performs addition from 1 to 499,999
9+
void* threadFunction1(void* args)
10+
{
11+
int i;
12+
long int localA = 0;
13+
for (int i = 1; i < 500000; i++)
14+
{
15+
a = a + i; // Update shared variable (not thread-safe)
16+
}
17+
return NULL;
18+
}
19+
20+
// Thread function 2 — performs addition from 1 to 1,000,000
21+
void* threadFunction2(void* args)
22+
{
23+
int i;
24+
long int localA = 0;
25+
for (i = 1; i <= 1000000; i++) {
26+
a = a + i; // Update shared variable (not thread-safe)
27+
}
28+
return NULL;
29+
}
30+
31+
int main(int argc, char** argv)
32+
{
33+
int i;
34+
pthread_t one, two;
35+
a = 0; // Initialize shared variable
36+
37+
// Simple loop performing addition without threads
38+
for(i = 1; i <= 500000; i++) {
39+
a = a + i;
40+
}
41+
42+
// Print final value (only single-threaded computation here)
43+
printf("Final value of a = %ld\n", a);
44+
45+
return 0;
46+
}
47+
48+
/*
49+
• Runs only a single-threaded loop in main() — threadFunction1 and threadFunction2 are defined but never used.
50+
• The final printed value of a comes only from the loop in main().
51+
• Essentially, it’s not concurrent; it’s just a regular summation program.
52+
• No thread creation (pthread_create) or joining (pthread_join) happens.
53+
54+
Result: predictable and consistent, because there’s no threading or race condition.
55+
*/

0 commit comments

Comments
 (0)