SlideShare a Scribd company logo
Shared Memory in C (with
Pthreads)
Understanding parallel programming with
shared memory
Number of threads: 4
Level: Intermediate
What is Shared Memory?
• Memory accessible by all threads in a process.
• Used in parallel computing for fast communication.
• Threads share global and heap data.
Why Use Shared Memory?
• Efficient data sharing compared to message passing.
• Low communication overhead.
• Commonly used with Pthreads and OpenMP.
Threads in C (Pthreads)
• Use pthread_create() to launch threads.
• Each thread runs a function in parallel.
• Threads share heap and global variables.
Shared Memory Model
• Each thread has its own stack.
• Heap and global sections are shared.
• Care needed to avoid race conditions.
Basic Pthread Program
• #include <pthread.h>
• pthread_create(), pthread_join() for managing threads.
• Code example shown in next slide.
C Code Snippet (Shared Memory Example)
• Example: Summing array elements using 4 threads.
• Each thread processes a segment of the array.
• Threads share the final result variable.
Code
#include <stdio.h>
#include <pthread.h>
#define THREAD_COUNT 4
#define ARRAY_SIZE 16
int array[ARRAY_SIZE]; // Shared array
long total_sum = 0; // Shared result variable
pthread_mutex_t lock; // Mutex for synchronization
void* sum_array(void* arg) {
int thread_id = *(int*)arg;
int start = thread_id * (ARRAY_SIZE / THREAD_COUNT);
int end = start + (ARRAY_SIZE / THREAD_COUNT);
long local_sum = 0;
for (int i = start; i < end; i++) {
local_sum += array[i];
}
// Update shared total_sum safely
pthread_mutex_lock(&lock);
total_sum += local_sum;
pthread_mutex_unlock(&lock);
return NULL;
}
int main() {
pthread_t threads[THREAD_COUNT];
int thread_ids[THREAD_COUNT];
pthread_mutex_init(&lock, NULL);
// Initialize array
for (int i = 0; i < ARRAY_SIZE; i++)
array[i] = i + 1; // Values 1 to 16
// Create threads
for (int i = 0; i < THREAD_COUNT; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, sum_array, &thread_ids[i]);
}
// Join threads
for (int i = 0; i < THREAD_COUNT; i++)
pthread_join(threads[i], NULL);
pthread_mutex_destroy(&lock);
printf("Total sum = %ldn", total_sum);
return 0;
}
Synchronization Need
• Shared variables require synchronization.
• Mutex locks prevent race conditions.
• Barriers ensure threads wait for each other.
Pthread Mutex
• pthread_mutex_t lock;
• pthread_mutex_lock() / pthread_mutex_unlock()
• Used to control access to shared resources.
Shared Memory with Threads
.
Parallel Sum Example Diagram
• Array split into 4 chunks.
• Each thread processes a chunk in parallel.
• Results combined in a shared variable.
Performance Considerations
• Speedup = T_serial / T_parallel.
• More threads → less time (up to a point).
• Overhead of synchronization and context switching.
Runtime vs Threads (Graph)
• Graph: 1, 2, 4, 8 threads.
• Shows performance improvement.
• Plateau due to overhead.
Avoiding Pitfalls
• Avoid deadlocks by correct locking order.
• Minimize false sharing (cache line conflicts).
• Free resources properly.
Shared vs Message Passing
• Shared memory: low overhead, but risk of data races.
• Message passing (MPI): safer but slower.
• Choosing depends on application.
Summary of Key Points
• Shared memory allows fast inter-thread communication.
• Pthreads offer powerful thread control.
• Performance depends on synchronization and workload.

More Related Content

PPTX
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
PDF
chap7_slidesforparallelcomputingananthgrama
PDF
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf
PPT
Shared Memory Programming with Pthreads (1).ppt
PDF
System Programming - Threading
PPT
Chap7 slides
PDF
Multithreaded Programming Part- II.pdf
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
chap7_slidesforparallelcomputingananthgrama
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf
Shared Memory Programming with Pthreads (1).ppt
System Programming - Threading
Chap7 slides
Multithreaded Programming Part- II.pdf

Similar to shared_memory_c_program_in_Parallel Computing .pptx (20)

PPT
PPTX
Shared Memory Programming with Pthreads and OpenMP
PPT
Threaded Programming
PPTX
25-MPI-OpenMP.pptx
PPTX
24-sync-basic.pptx
PPT
Google: Cluster computing and MapReduce: Introduction to Distributed System D...
PDF
Pthread
PPTX
Threads and multi threading
PDF
Operating Systems - Advanced Synchronization
PPTX
Parallel Computing - openMP -- Lecture 5
PDF
Basic Multithreading using Posix Threads
PPTX
multithread in multiprocessor architecture
PDF
Example : parallelize a simple problem
PPTX
Lecture Semaphore Locks and Semaphores.pptx
PDF
parallel-computation.pdf
PPTX
openmp final2.pptx
PDF
Os Lamothe
PDF
Parallel computation
PPTX
Engineeering Operating systemsOS UNIT 3 Threads.pptx
PPT
slides8 SharedMemory.ppt
Shared Memory Programming with Pthreads and OpenMP
Threaded Programming
25-MPI-OpenMP.pptx
24-sync-basic.pptx
Google: Cluster computing and MapReduce: Introduction to Distributed System D...
Pthread
Threads and multi threading
Operating Systems - Advanced Synchronization
Parallel Computing - openMP -- Lecture 5
Basic Multithreading using Posix Threads
multithread in multiprocessor architecture
Example : parallelize a simple problem
Lecture Semaphore Locks and Semaphores.pptx
parallel-computation.pdf
openmp final2.pptx
Os Lamothe
Parallel computation
Engineeering Operating systemsOS UNIT 3 Threads.pptx
slides8 SharedMemory.ppt
Ad

Recently uploaded (20)

PPTX
Presentation on HIE in infants and its manifestations
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
RMMM.pdf make it easy to upload and study
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Institutional Correction lecture only . . .
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Presentation on HIE in infants and its manifestations
Abdominal Access Techniques with Prof. Dr. R K Mishra
O5-L3 Freight Transport Ops (International) V1.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
human mycosis Human fungal infections are called human mycosis..pptx
RMMM.pdf make it easy to upload and study
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Institutional Correction lecture only . . .
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Pharma ospi slides which help in ospi learning
102 student loan defaulters named and shamed – Is someone you know on the list?
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Final Presentation General Medicine 03-08-2024.pptx
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Ad

shared_memory_c_program_in_Parallel Computing .pptx

  • 1. Shared Memory in C (with Pthreads) Understanding parallel programming with shared memory Number of threads: 4 Level: Intermediate
  • 2. What is Shared Memory? • Memory accessible by all threads in a process. • Used in parallel computing for fast communication. • Threads share global and heap data.
  • 3. Why Use Shared Memory? • Efficient data sharing compared to message passing. • Low communication overhead. • Commonly used with Pthreads and OpenMP.
  • 4. Threads in C (Pthreads) • Use pthread_create() to launch threads. • Each thread runs a function in parallel. • Threads share heap and global variables.
  • 5. Shared Memory Model • Each thread has its own stack. • Heap and global sections are shared. • Care needed to avoid race conditions.
  • 6. Basic Pthread Program • #include <pthread.h> • pthread_create(), pthread_join() for managing threads. • Code example shown in next slide.
  • 7. C Code Snippet (Shared Memory Example) • Example: Summing array elements using 4 threads. • Each thread processes a segment of the array. • Threads share the final result variable. Code #include <stdio.h> #include <pthread.h> #define THREAD_COUNT 4 #define ARRAY_SIZE 16 int array[ARRAY_SIZE]; // Shared array long total_sum = 0; // Shared result variable pthread_mutex_t lock; // Mutex for synchronization void* sum_array(void* arg) { int thread_id = *(int*)arg; int start = thread_id * (ARRAY_SIZE / THREAD_COUNT); int end = start + (ARRAY_SIZE / THREAD_COUNT);
  • 8. long local_sum = 0; for (int i = start; i < end; i++) { local_sum += array[i]; } // Update shared total_sum safely pthread_mutex_lock(&lock); total_sum += local_sum; pthread_mutex_unlock(&lock); return NULL; }
  • 9. int main() { pthread_t threads[THREAD_COUNT]; int thread_ids[THREAD_COUNT]; pthread_mutex_init(&lock, NULL); // Initialize array for (int i = 0; i < ARRAY_SIZE; i++) array[i] = i + 1; // Values 1 to 16 // Create threads for (int i = 0; i < THREAD_COUNT; i++) { thread_ids[i] = i; pthread_create(&threads[i], NULL, sum_array, &thread_ids[i]); } // Join threads for (int i = 0; i < THREAD_COUNT; i++) pthread_join(threads[i], NULL); pthread_mutex_destroy(&lock); printf("Total sum = %ldn", total_sum); return 0; }
  • 10. Synchronization Need • Shared variables require synchronization. • Mutex locks prevent race conditions. • Barriers ensure threads wait for each other.
  • 11. Pthread Mutex • pthread_mutex_t lock; • pthread_mutex_lock() / pthread_mutex_unlock() • Used to control access to shared resources.
  • 12. Shared Memory with Threads .
  • 13. Parallel Sum Example Diagram • Array split into 4 chunks. • Each thread processes a chunk in parallel. • Results combined in a shared variable.
  • 14. Performance Considerations • Speedup = T_serial / T_parallel. • More threads → less time (up to a point). • Overhead of synchronization and context switching.
  • 15. Runtime vs Threads (Graph) • Graph: 1, 2, 4, 8 threads. • Shows performance improvement. • Plateau due to overhead.
  • 16. Avoiding Pitfalls • Avoid deadlocks by correct locking order. • Minimize false sharing (cache line conflicts). • Free resources properly.
  • 17. Shared vs Message Passing • Shared memory: low overhead, but risk of data races. • Message passing (MPI): safer but slower. • Choosing depends on application.
  • 18. Summary of Key Points • Shared memory allows fast inter-thread communication. • Pthreads offer powerful thread control. • Performance depends on synchronization and workload.