Shared-Memory Programming with Pthreads

In shared-memory programming, an instance of a program running on a processor is usually called a thread(unlike MPI, where it’s called a process).

POSIX is a standard for Unix-like operating systems–for example, Linux and Mac OS X. It specified a variety of facilities that should be available in such systems. In particular, it specifies an application programming interface(API) for multithreaded programming.

Sepmaphores can be thought of as a special type of unsigned int, so they can take on the values 0,1,2….
Note that sempahores are not part of Pthreads. Hence, it’s necessary to add the following preprocessor directive to any any program that uses them.

#include <semaphore.h>

A thread that executes sem_wait will block if the semaphore is 0. If the semaphore is not nonzero, it will decrement the semaphore and proceed. After executing the code in the critical section, a thread calls sem_post, which increments the semaphore, and a thread waiting in sem_wait can proceed.

4.8 Barriers and Condition Variables

Synchronzing the threads by making sure that they all are the same point in a program. Such a point of synchronization is called a barrier because no thread can proceed beyond the barrier until all the threads have reached it.

There are three ways to implement barriers. They are busy-waiting and a mutex, semaphores and condition variables. A condition variable can be used to implement barriers. A condition variable is a data object that allows a thread to suspend execution until a certain event or condition occurs. When the event or condition occurs another thread can signal the thread to “wake up.” A condition variable is always associated with a mutex.

猜你喜欢

转载自blog.csdn.net/lilele12211104/article/details/79074265
今日推荐