Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Peter Pacheco
Chapter 4
Shared Memory Programming
with Pthreads
# Chapter Subtitle
Roadmap
POSIX Threads
Caveat
10
. / pth_hello 4
Hello from the main thread
Hello from thread 0 of 4
Hello from thread 1 of 4
Hello from thread 2 of 4
Hello from thread 3 of 4
Copyright 2010, Elsevier Inc. All rights Reserved
11
Global variables
Shared variables.
12
13
One object
for each
thread.
int pthread_create (
pthread_t* thread_p /* out */ ,
const pthread_attr_t* attr_p /* in */ ,
void* (*start_routine ) ( void ) /* in */ ,
void* arg_p /* in */ ) ;
Copyright 2010, Elsevier Inc. All rights Reserved
14
pthread_t objects
Opaque
The actual data that they store is systemspecific.
Their data members arent directly accessible
to user code.
However, the Pthreads standard guarantees
that a pthread_t object does store enough
information to uniquely identify the thread with
which its associated.
15
16
17
Prototype:
void* thread_function ( void* args_p ) ;
18
19
20
MATRIX-VECTOR
MULTIPLICATION IN PTHREADS
Copyright 2010, Elsevier Inc. All rights Reserved
21
Serial pseudo-code
22
Using 3 Pthreads
thread 0
general case
23
24
CRITICAL SECTIONS
25
Estimating
26
27
28
29
Busy-Waiting
30
31
32
33
Mutexes
34
Mutexes
35
Mutexes
36
Mutexes
37
38
39
40
41
PRODUCER-CONSUMER
SYNCHRONIZATION AND
SEMAPHORES
Copyright 2010, Elsevier Inc. All rights Reserved
42
Issues
43
44
45
46
47
Barriers
48
49
50
51
52
53
Condition Variables
54
Condition Variables
55
56
READ-WRITE LOCKS
57
58
Linked Lists
59
60
61
62
63
64
65
66
Solution #1
67
Issues
68
Solution #2
69
Issues
70
71
72
73
74
75
76
77
100,000 ops/thread
99.9% Member
0.05% Insert
0.05% Delete
78
100,000 ops/thread
80% Member
10% Insert
10% Delete
79
80
81
82
THREAD-SAFETY
83
Thread-Safety
84
Example
85
Simple approach
86
Simple approach
87
88
89
90
91
92
Oops!
93
What happened?
94
What happened?
95
96
97
98
99
100
101
102
103
104
105