Skip to content

Commit 4026d79

Browse files
committed
perf: optimize pthread mutex usage with local accumulation
Refactored pthread thread functions to use local accumulation (localA) before a single synchronized update to the shared variable 'a'. Reduces lock contention and improves concurrency performance while maintaining correctness through coarse-grained mutex protection. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 7f991e0 commit 4026d79

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
/* Mutex protecting the shared variable `a` */
9+
static pthread_mutex_t a_mutex;
10+
11+
/* Thread function 1 — performs addition from 1 to 499,999 */
12+
void* threadFunction1(void* args)
13+
{
14+
long int localA = 0; // Missing variable declaration
15+
16+
for (int i = 1; i < 500000; i++)
17+
{
18+
localA = localA + i;
19+
}
20+
21+
pthread_mutex_lock(&a_mutex);
22+
a = a + localA;
23+
pthread_mutex_unlock(&a_mutex);
24+
25+
return NULL; // Always return something from void* thread functions
26+
}
27+
28+
/* Thread function 2 — performs addition from 1 to 1,000,000 */
29+
void* threadFunction2(void* args)
30+
{
31+
long int localA = 0;
32+
33+
for (int i = 1; i <= 1000000; i++)
34+
{
35+
localA = localA + i;
36+
}
37+
38+
pthread_mutex_lock(&a_mutex);
39+
a = a + localA;
40+
pthread_mutex_unlock(&a_mutex);
41+
42+
return NULL;
43+
}
44+
45+
int main(int argc, char** argv)
46+
{
47+
pthread_t one, two;
48+
49+
/* Initialize the mutex before using it */
50+
pthread_mutex_init(&a_mutex, NULL);
51+
52+
/* Create two threads that run concurrently */
53+
pthread_create(&one, NULL, threadFunction1, NULL);
54+
pthread_create(&two, NULL, threadFunction2, NULL);
55+
56+
/* Wait for both threads to complete */
57+
pthread_join(one, NULL);
58+
pthread_join(two, NULL);
59+
60+
printf("Final value of a = %ld\n", a);
61+
62+
pthread_mutex_destroy(&a_mutex);
63+
64+
return 0;
65+
}

0 commit comments

Comments
 (0)