Lecture 5
Lecture 5
Computing
Lecture 5 Parallel Programming
Matrix-Vector Multiplication
Pseudocode for serial matrix-vector multiplication
Critical Sections
Busy Wait
Busy Wait
Mutex
Issues
• First barrier
– Threads use a busy-wait loop (while(counter <
thread_count)) to wait for all threads to reach the barrier,
threads consume CPU cycles while waiting
• Second barrier
– Reusing the same counter variable causes unsynchronized
behavior.
– At the start of the second barrier, counter =
thread_count from the first barrier, making the condition
counter < thread_count immediately false.
– As a result, threads bypass the second barrier, leading to
unsynchronized execution.
Contd…
• Int counter: Tracks the number of threads that have reached the
barrier.
• pthread_mutex_t mutex: Protects access to the shared counter to
prevent race conditions.
• pthread_cond_t cond_var: Used for condition-based synchronization
(to block and wake threads).
• pthread_mutex_lock(&mutex) locks the mutex to protect shared data.
• The counter is incremented by the thread to indicate it has reached the
barrier.
• If the counter equals thread_count, it means all threads have reached
the barrier. The thread resets the counter to 0.It then broadcasts a
signal using pthread_cond_broadcast(&cond_var) to wake all threads
waiting at the barrier.
• If the thread is not the last to reach the barrier, it waits on the condition
Pthreads Read-Write Locks
• int pthread_rwlock_rdlock(pthread_rwlock_t
*rwlock_p);
• int pthread_rwlock_tryrdlock(pthread_rwlock_t
*rwlock_p);
• int pthread_rwlock_wrlock(pthread_rwlock_t
*rwlock_p);
• int pthread_rwlock_trywrlock(pthread_rwlock_t
*rwlock_p);
• int pthread_rwlock_unlock(pthread_rwlock_t
*rwlock_p);
• int pthread_rwlock_init(pthread_rwlock_t
*rwlock_p,
Thread-Safety
• Divide the input file into lines of text and assign the
lines to the threads in a round-robin fashion.
• The first line goes to thread 0, the second goes to
thread 1,…, the nth goes to thread n, the n +1st goes
to thread 0, etc.
• We can serialize access to the lines of input using
semaphores.
• After a thread has read a single line of input, it can
tokenize the line using the C standard library
"strtok()" function.
The strtok() function