Synchronizing threads
In general,
each thread must take special care in using resources that might be concurrently
used by another thread.
NOTE:
The definition of ``resource'' will vary with applications.
Typically, ``resources'' are manifested as some organization
of data relevant to the application in process memory
(perhaps a linked list or other data structure) or in files.
Unless their actions are synchronized,
threads may encounter logically inconsistent
linked lists or partially updated structures in common process memory.
Synchronization may also be needed for concurrent actions on commonly
held external resources such as file descriptors and message queues.
-
There is no automatic, implicit mechanism to protect each thread from the actions
of other threads.
The correctness of a multithreaded program must be incorporated into the design
by having each thread cooperate with the others.
-
The Threads Library provides a suite of functions with several categories
of synchronization semantics.
The categories are:
-
Locks
-
Semaphores
-
Barriers
-
Condition Variables
Most of these categories contain several variants.
-
The programmer has the responsibility to:
-
use the correct number and type of synchronization mechanism(s)
-
use them where needed
-
enforce synchronization on every thread using the common resource
-
avoid deadlock and starvation conditions
-
Other than programmer discipline,
there is nothing to stop any thread from using common resources without
obeying the synchronization protocol being used by the others.
-
The general procedure for using these mechanisms is:
-
Allocate a synchronization data structure for the resource to be protected
(for example,
to use a mutual exclusion lock, allocate a structure of type mutex_t).
The address of that structure becomes an argument for all subsequent operations
on this instance of the mechanism.
-
Initialize the mechanism.
-
Use the mechanism.
-
Deallocate the mechanism when it is no longer needed --
perhaps when the resource being protected is deallocated.
Next topic:
Locks
Previous topic:
Managing thread scheduling
© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004