Information Technology Reference
In-Depth Information
and write multiple variables just as a single-threaded version would.
Critical sections. A sequence of code that operates on shared state is a
critical section. A critical section is a sequence of code that atomically accesses
Definition: critical section
shared state. By ensuring that an object's lock is held while any of its critical
sections is executed, we can ensure that each critical section on a collection of
shared state appears to execute atomically.
Example: For the TSQueue class in Figure 5.3, the methods tryInsert()
and tryRemove() each include a critical section that manipulates several of a
TSQueue object's state variables ( items , nFull , firstFull , and nextEmpty .)
Notice two things:
Each class may define multiple methods that operate on the shared state
defined by the class, so there may be multiple critical sections per class.
However, for each instance of the class (i.e., for each object) only one
thread holds the object's lock, only one thread is actively executing any of
the critical sections per shared object instance.
Example: For the TSQueue class in Figure 5.3, if one thread calls
queue1.tryInsert() and another thread calls queue1.tryRemove() , ei-
ther the insert() will occur before the remove() or vice versa; these
functions' accesses to object queue1 's state variables will not be inter-
leaved.
A program may create multiple instances of a class. Each instance is a
shared object, and each shared object has its own lock. Thus, multiple
threads may be active in the critical sections for different shared object
instances.
Example: For the TSQueue class in Figure 5.3 and instances of that
class in Figure 5.4, if one thread calls queue1.tryInsert() , another
thread calls queue2.tryRemove() , and a third thread calls queue3.tryInsert() ,
all three threads may be simultaneously executing critical section code
operating on different instances of the TSQueue class.
Using shared objects. Shared objects are allocated the same ways other
objects|they can be dynamically allocated from the heap using malloc() and
new() or they can be statically allocated in global memory by declaring static
variables in the program.
Multiple threads need to be able to access shared objects. If shared objects
are global variables, then a thread's code can just refer to an objects global name
to reference it; the compiler computes the corresponding address. If shared ob-
jects are dynamically allocated, then each thread that uses an object needs a
 
Search WWH ::




Custom Search