Skip to content

Commit 7f991e0

Browse files
committed
feat: add pthread mutex-based thread synchronization example
Implemented a thread-safe C program using pthread_mutex_t to protect a shared global variable from concurrent updates. Demonstrates critical section control with pthread_mutex_lock/unlock and includes concise C vs Java mutex explanation. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent db9804f commit 7f991e0

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
for (int i = 1; i < 500000; i++)
15+
{
16+
pthread_mutex_lock(&a_mutex);
17+
a = a + i;
18+
pthread_mutex_unlock(&a_mutex);
19+
}
20+
return NULL;
21+
}
22+
23+
/* Thread function 2 — performs addition from 1 to 1,000,000 */
24+
void* threadFunction2(void* args)
25+
{
26+
for (int i = 1; i <= 1000000; i++)
27+
{
28+
pthread_mutex_lock(&a_mutex);
29+
a = a + i;
30+
pthread_mutex_unlock(&a_mutex);
31+
}
32+
return NULL;
33+
}
34+
35+
int main(int argc, char** argv)
36+
{
37+
pthread_t one, two;
38+
39+
pthread_mutex_init(&a_mutex, NULL);
40+
41+
pthread_create(&one, NULL, threadFunction1, NULL);
42+
pthread_create(&two, NULL, threadFunction2, NULL);
43+
44+
pthread_join(one, NULL);
45+
pthread_join(two, NULL);
46+
47+
printf("Final value of a = %ld\n", a);
48+
49+
pthread_mutex_destroy(&a_mutex);
50+
return 0;
51+
}
52+
53+
/*
54+
• The mutex a_mutex ensures that updates to a are serialized so no two threads write a at the same time.
55+
• pthread_mutex_lock / pthread_mutex_unlock bracket the critical section that updates the shared state.
56+
57+
Small info: What is a mutex (C vs Java) — concise
58+
• C (pthread): a pthread_mutex_t is a kernel-aware or user-space primitive (implementation detail)
59+
used to ensure mutual exclusion.
60+
Threads call pthread_mutex_lock() to enter the critical section and pthread_mutex_unlock() to leave it.
61+
It prevents data races on shared memory.
62+
• Java: synchronized (monitor) and java.util.concurrent.locks.
63+
Lock provide mutual exclusion at the JVM level. synchronized(obj){...} implicitly acquires/releases an
64+
object monitor; ReentrantLock is an explicit lock with richer semantics.
65+
Under the hood, JVM monitors map to OS synchronization primitives (futex/mutex) or optimized user-space mechanisms.
66+
*/

0 commit comments

Comments
 (0)