



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Basics of Shared Memory Programming with Pthreads
Shared mem same as OpenMP (race cond, etc). Topics (Ch 7.3-7.9):
What are pthreads, and pthread basics
Starting, joining and exiting threads
Pthreads example with dot product
Pthreads error handling
Challenges in using Pthreads standard
Mutual exclusion using mutexes
Awaiting an event using condition variables
Etc.
What is Pthreads?
Pthreads
(POSIX [Portable Operating System Interface] threads):
An
pthread.hIt consists of a ANSI/ISO C API, with appropriate CPP/typedefs inIEEE operating system interface standard (POSIX Section 1003.1c).
Does the same stuff as OpenMP, but at much lower level:
Preceeded OpenMP (standard 1995, threads around longer)
Some OpenMP implementations actually devolve to pthread calls
Lower level & quite a bit grungier than OpenMP
Requires minimal compiler support:
need lib, header file, and thread-safe system libs
Available on almost all platforms, including gcc
More info:
http://www.llnl.gov/computing/tutorials/pthreads/
Sections 7.3-7.9 of textbook
Pthreads Programming
(O’Reilly) by Nichols, Buttlar, & Farrell
Stupendously Basic Basics
Almost all parallel programs need to answer the following questions:
→How do I set nthreads to use?
How many (successful) calls to
pthread
create
did you make?
→How many threads are running?
See above.
→Which thread am I?
Err, you passed that in when you called
pthread
create
, right?
Can get thread handle (not rank) wt
pthread
t pthread
self()
→How do I start parallel threads?
That would be:
pthread
create
→How do I join threads & their results back to serial?
Join them up using
pthread
join
Add them up yourself, shared memory boy!
→How can I synchronize threads?
mutex / condition variables (later)
→How can a thread finish execution?
Just finish execution (return of threaded route is thread ret val)
pthread
exit(void *ret)
Pthread creation, finish
pthread
create
Creates thread with attribute attr (NULL uses
defaults);
new thread starts exec in
start
routine
and is passed
int pthread_create(single void pointer arg (very convenient!).
// Non-zero means error
pthread_t *thread,
// returns thread’s struct
const pthread_attr_t *attr,
// Attributes, NULL for defaults
void (start_routine)(void*),
// Routine to start executing
void *arg
)
// Ptr arg to start_routine
pthread
join
: Block until thread terminates
int pthread_join(
// Non-zero means error
pthread_t thread
// Thread to join
void **val_ptr)
// Return value from joined thread
pthread
exit
: Terminates thread; use
exit()
to term all
threads
void pthread_exit(
void *value)
// Return val given to pthread_join caller
Pthreads are not required to join or call
pthread
exit
Threads that are never joined can avoid overhead wt the
detached
attribute
All pthreads
peers
(can create new threads, kill old, etc)
Can spawn threads in
log
2 ( p ) overhead wt tree strategy!
Parallelizing Simple Dot Product (Intro)
Will use simple dot product to illustrate simplist Pthreads use.
There
are two approaches:
Remember the good old days (they are gone):
serial code
1 d o u b l e
d d o t ( i n t
N ,
d o u b l e
∗ X ,
2
d o u b l e
∗ Y )
3 (^) {
4
d o u b l e
d o t ;
5
i n t
i ;
76
d o t
=
X [ 0 ]
∗
Y [ 0 ] ;
8
f o r
( i =1;
i
<
N ;
i ++)
9
d o t
+= X [ i ]
∗
Y [ i ] ;
0
r e t u r n ( d o t ) ;
1 (^) }
OpenMP code
1 d o u b l e
d d o t ( i n t
N ,
d o u b l e
∗ X ,
2
d o u b l e
∗ Y )
3 (^) {
4
d o u b l e
d o t ;
5
i n t
i ;
76
d o t
=
X [ 0 ]
∗
Y [ 0 ] ;
8
#pragma
omp
p a r a l l e l
f o r
\
9
r e d u c t i o n ( + : d o t )
10
f o r
( i =1;
i
<
N ;
i ++)
11
d o t
+= X [ i ]
∗
Y [ i ] ;
12
r e t u r n ( d o t ) ;
13
(^) }
Simple Master-slave Dot Product wt Pthreads
struct dot_struct{ #include <pthread.h>
int N;double *Y;double *X;double dotout;
{void *ddot_serial(void *vds)};
{if (N > 0)N = ds->N;struct dot_struct *ds = vds;double *X, *Y, dot;int i, N;
for (i=1; i < N; i++)dot = X[0] * Y[0];Y = ds->Y;X = ds->X;
dot += X[i] * Y[i];
ds->dotout = dot;
return(NULL);else ds->dotout = 0.0;}
}
double ddot_pt(int NT, int N, double *X, double *Y) {
for (i=1; i < NT; i++) {n = N / NT;mythrs = malloc(sizeof(pthread_t)(NT-1));dss = malloc(sizeof(struct dot_struct)(NT));struct dot_struct *dss;pthread_t *mythrs;int i, n;double dot;
Y += dss[i].N;X += dss[i].N;pthread_create(mythrs+i-1, NULL, ddot_serial, dss+i);dss[i].X = X; dss[i].Y = Y;dss[i].N = (i != 1)? n : n + N - n*NT;
for (i=1; i < NT; i++) {dot = dss[0].dotout;ddot_serial(dss);dss[0].N = n; dss[0].X = X; dss[0].Y = Y;}
dot += dss[i].dotout;pthread_join(mythrs[i-1], NULL);
return(dot);free(mythrs);free(dss);}
}
Pthreads Error Messages
Most pthread routines return error condition:
0 means no error, each routine can return different errors:
pthread
create
(no recsources),
(bad attr val),
(insuff permission)
pthread
join
(thr not joinable),
(can’t find thr)
Use
man <pthread_rout>
to find error names
Must include
<errno.h>
to test using names
Most systems provide
strerror
in
<string.h>
if ( ierr = pthread_create(...) ) {#include <errno.h> #include <pthread.h>
if (ierr == EAGAIN)
fprintf(stderr,
LINE, FILE);"Insufficient resources, %d of %s!\n"
if (ierr == EINVAL)
fprintf(stderr,
LINE, FILE);"Bad arg to pthread_create, %d of %s\n",
else
fprintf(stderr,
ierr, LINE, FILE);"Error %d to pthread_create, %d of %s\n",
exit(ierr);
}
{if ( ierr = pthread_create(...) )#include <string.h>#include <errno.h>#include <pthread.h>
fprintf(stderr,
strerror(ierr));LINE, FILE,"Error line %d of %s: %s\n",
exit(ierr);
}
Pthreads Challenges
standard flags (even always using gcc):Must indicate thread use for compilation & linking (why?), but no
Comp/link:
-pthreads -pthread
-mt
libs :
-lpthread
, nothing
Standard has nothing to say on some very important issues:
How to tell system to spawn thread to particular node (diff, same)
How to tie process to node
No standard way (that I know) to get # of physical procs
Many things that are specified are optional, and thus fairly useless
At least in old days, vendors often violate standard:
Must use attribute to guarantee default thread state
Must use non-standard names to get correct behavior
Be prepared to use
man
: compiler (search
thread
pthreads
Mutex Gotchas
Ensure mutex protective wt no deadlocks (not always easy!)
Instead of
pthread
mutex
trylock
, should I spawn another thread?
If lrg data struc (eg tree), may want heir of locks (eg., lock subtree):
awaiting each other’s release. 2 procs, 2 locks:quired in same direction, preventing deadlock due to two locksMust force ordering of lock acquisition, so that all locks are ac-
deadlock
(deadly embrace
may be too restrictive/expensive (so use another solution):Putting a mutex around every shared data structure will work, but
Usually OK to have multiple readers, but only one writer
If we spend a lot of time awaiting lock, will waste CPU cycles
synchronization methods for complex structuresMutex often used for critical section, but often use more complicated
Why Condition Variables?
Mutex alone can be expensive:
Thread wastes a lot of CPU time sitting blocked on lock()
Thread wastes a lot of sys res by excessive polling wt trylock()
Costs can be much higher if multiple threads on one node:
Blocked/polling thread competes for CPU wt thread holding lock!
takes place (eg., more work in queue)Condition variables allow thread to yield execution until given event
→Cond vars have mutex associated with them
∗ (eg., task queue)Usually action taken after cond var depends on shared data struct
ensures coordination (example forthcoming)Want newly awoken threads to take coordinated action, mutex
to go back to sleepso checking data associated wt mutex can ensure we don’t wantThreads waiting on cond vars can be spuriously awoken by OS,
Basic Pthreads Condition Variable Routines
int pthread_cond_init(pthread_cond_t *cond,
const pthread_condattr_t *attr);
int pthread_cond_destroy(pthread_cond_t *cond);
pthread
cond
wait
: release mutex
mut
, suspend exec until another
thread signals on
cond
or OS wakes us (spurious); on wakeup, each
awakened thread blocks until
mut
reaquired
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mut);
pthread
cond
signal
: awakens
1 thread waiting on
cond
int pthread_cond_signal(pthread_cond_t *cond);
pthread
cond
broadcast
: awakens all threads waiting on
cond
int pthread_cond_broadcast(pthread_cond_t *cond);
Typically, signalling thread has
mut
locked when signalling, and re-
leases it directly after
Also a timed wait,
pthread
cond
timedwait()
Chunk Scheduled Work Pool using a Condition Variable
struct workq {
...
pthread_mutex_t#define THRESH 4#define CHUNK 16int nwork=0;} *workhead;
wqlock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t
wqcond = PTHREAD_COND_INITIALIZER;
void AddWork(struct workq *p) {
for(n=0,last=p; last->next;struct workq *last;
last = last->next, n++);
if (nwork == n)nwork += n;workhead = p;last->next = workhead;pthread_mutex_lock(&wqlock);
pthread_cond_broadcast(&wqcond);
pthread_mutex_unlock(&wqlock);
}
{void DoAllWork()
while(1) {int mynwork=0;struct workq *mywork;
if (mynwork == 0) {
while (!workhead)pthread_mutex_lock(&wqlock);
pthread_cond_wait(&wqcond, &wqlock);
LOCKED = 1;
else if (mynwork < THRESH && workhead)}
LOCKED = !pthread_mutex_trylock(&wqlock);
{if (LOCKED)
if (workhead)
mywork = GetWrkChunk(mywork,&mynwork);
pthread_mutex_unlock(&wqlock);
mynwork--;mywork = FreeWorkNode(mywork);DoThisWork(mywork);}
}
}
Building a Barrier
May need to have phase change, so barrier
t
threads running on
p
procs:
struct barrier {
int ndone;pthread_cond_t cond;pthread_mutex_t lock;
struct barrier *barrier_init(){}
return(p);p->ndone = 0;pthread_cond_init(&p->cond, NULL);pthread_mutex_init(&p->lock, NULL);p = malloc(sizeof(struct barrier));
void barrier(struct barrier *b) {}
if (++b->ndone < NT)pthread_mutex_lock(&b->lock, NULL);
while (b->ndone < NT)
pthread_cond_wait(&b->cond, &b->lock);
else
pthread_cond_broadcast(&b->cond);
pthread_mutex_unlock(&b->lock);
}
of struct in mem)!!!init() called by main (one copy
Cost:
(^) t
t
grab/rel of lock
to lack of syncProb not payed in full, due
t (^) −
(^) 1 grab/rel of lock
Payed in full!
Cost
t ) if
p
==
t
or
t ≫
(^) p
Can we get rid 2
nd
t ?
Clint’s Special ‘new-car-smell’ Extra-Cheap Barrier!
Barr req 1
st
t
sync, but not last, so what if we use a dummy lock so
everyone doesn’t sync on
b->lock
void barrier(struct barrier *b) {
pthread_mutex_t
dum = PTHREAD_MUTEX_INITIALIZER;
{if (++b->ndone < NT)pthread_mutex_lock(&b->lock, NULL);
while (b->ndone < NT)pthread_mutex_unlock(&b->lock)pthread_mutex_lock(&dum);
pthread_cond_wait(&b->cond, &dum);
pthread_mutex_unlock(&dum);
else {}
pthread_mutex_unlock(&b->lock);pthread_cond_broadcast(&b->cond);
}
cost toProb is competition for single lock/cond; show later how to reduce
(^) (
pt^
(^) log
2 ( p ) )
by using
(^2) t
lock/cond
p^ t
(^) log
2 ( p ))
Barrier (Pg 308)
typedef struct barrnode {
int count;pthread_cond_t OkGoUp, OkGoDown;pthread_mutex_t countlock;
typedef struct barrnode} mybarr_t;
my_lgbarr_t[NT];
void mybarr_init(my_lgbarr_t b) {
for (i=0; i < NT; i++) {
pthread_mutex_initb[i].count = 0;
(&b[i].countlock, NULL);
pthread_cond_init
(&b[i].OkGoUp, NULL);
pthread_cond_init
(&b[i].OkGoDown, NULL);
}
void my_lgbarrier}
do {i = 2; base = 0;(my_lgbarr_t b, int Iam) {
k = base + Iam / i;
if (Iam%i == 0) { // even stay in
while (c[k].count < 2)b[k].count++;pthread_mutex_lock(&b[k].countlock);
pthread_cond_wait(&b[k].OkGoUp, &b[k].countlock)
pthread_mutex_unlock(&b[k].countlock);
} else {
// odd nodes signal & leave
if (b[k].count == 2)b[k].count++;pthread_mutex_lock(&b[k].countlock);
pthread_cond_signal(&b[k].OkGoUp)
while (b[k].count != 0)
pthread_cond_wait(&b[k].OkGoDown, &b[k].countlock)
break;pthread_mutex_unlock(&b[k].countlock);
i *= 2;base += NT/i;}
for(i /= 2; i > 1; i /= 2) {} while (i <= NT);
pthread_cond_signal(&b[k].OkGoDown)pthread_mutex_unlock(&b[k].countlock);b[k].count = 0;pthread_mutex_lock(&b[k].countlock);k = base + Iam/i;base = base - NT/i;
}
}
Log vs linear Barrier on 32 Nodes
Log barrier doesn’t have true log shape; why?
Shared Memory Gotchas
Cannot assume any part order/schedule you don’t enforce wt sync
Even if it always works on OS A, may deadlock OS B
may not run again for arbitrary amount of timeRemember thread may be context-switched out at any time, and
more likely, but explicitly enforce it if requiredUse scheduling & priority to make part thread’s CPU domination
No amount of normal testing guarantees correct program
Decent test tech is to artificially delay each node in tests in turn
Same var name only points to same mem space if you guarantee it
Stack is local, regardless of name
Heap global, but be sure you did one global malloc, not
p
local!
Ensure mult locks/cond vars don’t cause deadly embrace
cally, allocating process owns data)On NUMA systems, may want to figure out allocation policy (typi-
Duplicate data to avoid sync when possible
Remember to check you use thread-safe libraries
Target opt to common case (shared or solo processors)