COMP5426 Distributed
Programming Shared Memory
(Pthread Basic
Copyright By PowCoder代写 加微信 powcoder
Synchroniz
my_cost < best_cost)
best_cost = my_cost;
Assume that there are two
best_cost is 100, and the v
5 at threads t1 and t2.
Depending on the schedule best_cost could be 50 or 7
When multiple threads attempt to manipulate the same data item, the results can often be incoherent if proper
care is not taken to synchronize them.
/* each thread trie follows */
s to update
threads, t
best_cost as
he initial
alues of my_cost are 50 and
of the threads, the value of 5 - A race condition problem!
Race Condition
not assume a
Any such order must be explicitly establis synchronization mechanisms.
where the final result d ion of the processes.
who finishes the race last.
of execution.
A race condition occurs when
Multiple processes or threads read and data items
Theydosoinaway the order of execut
The output depends on
"mutex", which is an abbreviation for "mutual exclusion".
with synchronization
r creating, destroyin
They are also supplemented by mutex attribute or modify attributes associated with mutexes.
When a process, or thread executes code that manipulates shared data, we say it is in its Critical Section.
A general structure for critical section:
...lock mutex
critical section
unlock mutex noncritical s
g, locking and
Mutex must and must be
be declared with type pthread_mutex_t initialized before they can be used.
There are two ways to initialize a mutex variable: Statically, when it is declared. For example:
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
Dynamically, with the pthread_mutex_init() routine. This method permits setting mutex object attributes, attr (which may be
specified as NULL
pthread_mutex_init (mutex,attr) pthread_mutex_destroy (mutex) pthread_mutexattr_init (attr)
pthread_mutexattr_destroy (attr)
The mutex is initially u
cept defaults).
pthread_mutex_trylock (mut
pthread_mutex_lock (mutex) pthread_mutex_unlock (mutex)
pthread_mutex_lock() is used by a thread to acquire a lock on the specified mutex variable.
pthread_mutex_unlock() will unlock a mutex if called by the owning thread. An error will be returned if:
themutexwasalreadyunlocked
themutexisownedbyanotherthread
pthread_mutex_tr
ylock() will attemp
the mutex is already locked, the routine with an “EBUSY" error code. This routin preventing deadlock conditions.
t to lock a mutex. Howeve
will return immediat e may be useful in
write our previously inc
pthread_mutex_t minimum_value_lock;
int best_cost; //global variable! main() {
pthread_mut
ex_init(&minimu
}void *find_min(void ....
pthread_mutex_lock(&minimum
if (my_cost < best_cost) best_cost = my_cost;
*list_ptr) {
hread_mutex_unlock(&minimum_value_l
code segment
The producer-consume constraints:
The producer
buffer when the previous task by a consumer thread.
The consumer thr
there is some
structure.
Individual consumer
r scenario im
thread must
eads must no
thing present in the shared
poses the following
overwrite the shared
has not been picked up
pthread_mutex_t
int task_available
.... task_avai
lable = 0;
task_queue_lock;
pthread_mutex_init(&task_qu
eue_lock, NULL);
*producer_thread_
void *producer(void ....
while (!done()) { inserted = 0;
create_task(&my_task); while (inserted == 0) {
pthread_mutex_lock(&task_queu
if (task_available == 0) { insert_into_queue(my_task); task_available = 1;
inserted = 1;
}pthread_mutex_unlock(&task_queue_lock);
ocess_task
onsumer_thread
void *consumer(void ...
while (!done()) { extracted = 0;
while (extracted == 0) {
pthread_mutex_lock(&task_qu
if (task_available == 1) { extract_from_queue(&my_task); task_available = 0;
extracted = 1;
}pthread_mutex_unlock(&task_
queue_lock);
Encapsulating
within locks can degradation.
ritical sections must be
one after another.
of Locking
ocks represent serialization points since
t is often possible to reduce the idling
verhead associ
thread_mutex_trylock.
executed by
ated with locks using
significant performance
Alleviating
/* using pthread_mutex_trylock routine */
...Pthread_mutax_t tryLock_lock = PTHREAD_MUTEX_INITIALIZER;
...lock_status=pthread_mutex_trylock(&tryLock_lock if (lock_status == EBUSY) {
/* do something else */ ...
}e l s e { /* d
o one thing */
ead_mutex_u
nlock(&tryLock_lock);
Mutexs pr However,
One bad thread (or one pr
can kill the whole system.
Unnecessary busy-waiting
Lock() and unlock() are scattered among
Monitor is a high-level abstraction that may
provide a convenient and effective mechanism
or thread synchronization
several threads. Therefore, it is difficult to
understand their effects
Usage must be correct in all the thre
synchronization
Local data variables are accessible only
thread enters monitor by invoking
procedures Only one thread
may be executing
the monitor at a time
Monitor does not need to code certain
constraints explicitly.
However, it is not sufficiently powerful for modeling some other synchronizatio
An additional synchronization mechanism, i.e., condition variable, required.
The third class of between threads t
A condition variable has a queue for those thre
waiting the corresponding event to occur to wait on.
If another
signals the
functions address communications hat share a mutex.
A condition variable allows a thread to block specified data reaches a predefined state.
A condition variable indicates an event and has no value.
One cannot store a value into nor retrieve a value from a condition variable.
If a thread must wait for an event to occur, on the corresponding condition variable.
thread causes the event to occur, that thread simp
corresponding condition v
thread waits
This class and signal
includ based
to set/que
also included.
A condition variable is
mutex lock.
es functions to upon specified
create, dest variable valu
e attributes are
n conjunction with a
Creating & Destroyin
Condition variables must be declared with type pthread_cond_t, and must be initialized before they
can be used.
There are two w
Statically, when pthread_cond_t
Dynamically, with the pthread_cond_init() routine. This method
permits setting condition variable object attributes, attr (which
may be specified as NULL
pthread_cond_init (condition, attr) pthread_cond_destroy (condition) pthread_condattr_init (attr)
pthread_condattr
ays to initialize a condition varia
it is declared. For example: myconvar = PTHREAD_CON
accept defaults).
D_INITIALIZER;
Waiting and Signali
pthread_cond_ pthread_cond_
pthread_cond_
wait (condition, m signal (condition)
pthread_cond_wait() blocks the specified condition is signalled.
This routine should be called while mutex is locked, and it will automatically release the mutex while it waits.
After signal is received and thread is awakened, mutex will be automatically locked for use by the thread.
The programmer is then responsible for unlocking mutex when the thread is finished with it.
thread until
Waiting and Signali
pthread_cond_signal() is used another thread which is waiti
It should be called after mutex is locked, and
must unlock mutex in order for pthread_cond_wait() routine to complete.
thread_con
ds blocked
d_broadcast() routine unlocks all
on the condition
to signal (or wake u ng on the condition
Waiting and Signali
Proper locking and unlocking of variable is essential when using
the associated m these routines. F
Failing to lock the mutex before calling pthread_cond_wait() may cause it NOT to
Failing to unlock the mutex after calling pthread_cond_signal() may not allow a match pthread_cond_wait() routine to complete (it remain blocked).
Producer-Consumer
pthread_con
ion Variables
d_t cond_que
pthread_mutex_t task_queue_c
int task_available;
/* other data structu
res here */
/* declarations and
task_available = 0; pthread_cond_init(&cond_queue_empty, NULL); pthread_cond_init(&cond_queue_full, NULL);
pthread_mutex_init(&tas
/* create and
initializations
join producer
nd_queue_full;
ond_lock, NULL);
mer thread
Producer-Consumer
*producer(void
ion Variables
create_task();
pthread_con
pthread_mutex_unlo
*producer_thread_
d_signal(&cond_qu
ck(&task_que
eue_full);
ue_cond_lock
pthread_mutex_lock(&task_queue_cond_lock);
if (task_available == 1)
pthread_cond_wait(&cond_queue_empty &task_queue_cond_lock);
insert_into_queue(); task_available = 1;
Producer-Consumer
void *consume
ion Variables
my_task = e
while (!done()) {
pthread_mutex_lock(&task_queue_cond_lock);
if (task_available == 0)
pthread_cond_wait(&cond_queue_f
&task_queue_c
task_available = 0;
pthread_con
act_from_queue
d_signal(&cond_qu
pthread_mutex_unlock(&task_queue_cond_lock
process_task(my_task);
mer_thread_data)
ond_lock);
eue_empty);
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com