标签:
Before moving beyong locks, we will first describe how to use locks in some common data
structures. Adding locks to a data structure to make it usable by threads makes the structure
thread safe. Of course, exactly how such locks are added determines both the correctness
and performance of the data structure. And thus, our challenge:
CRUX: How To Add Locks To Data Structures
When given a particular data structure, how shoule we add locks to it, in order to make it work
correctly? Further, how do we add locks such that the data structure yields high performance,
enabling mang threads to access the structure at once, i.e., concurrently?
Of course, we will be hard pressed to cover all data structures or all methods for adding
concurrency, as this is a topic that has been studied for years, with literally thousands of
research papers published about it. Thus, we hope to provide a sufficient introduction to the
type of thinking required, and refer you to some good resources of material for further inquiry
on your own. We found Moir and Shavit‘s survey to be a great source of information.
Concurrent Counters
One of the simplest data structures is a counter, it is a structure that is commonly used and has
a simple interface. We define a simple nonconcurrent counter in Figure 29.1.
Simple But Not Scale
As you can see, the non-synchronized counter is a trivial data structure, requiring a tiny amount
of code to implement. We now have our next challenge: how can we make this code thread safe
? Figure 29.2 shows how we do so.
This concurrent counter is simple and works correctly. In face, it follows a design pattern
common to the simplest and most basic concurrent data structures: it simply adds a single
lock, which is acquired when calling a routne that manipulates the data structure, and is
released when returning from the call. In this manner, it is similar to a data structure built
with monitors, wherer locks are acquired and released automatically as you call and return
from object methods.
At this point, you have a working concurrent data structure. The problem you might have is
performance. If your data structure is too slow, you will have to do more than just add a single
lock; such optimization, if needed, are thus the topic of the rest of the chapter. Note that if the
data structure is not too slow, you are done! No need to do something fancy if something simple
will work.
To understand the performance costs of the simple approach, we run a benchmark in which
each thread updates a single shared counter a fixed number of times; we then vary the number
of threads. Figure 29.3 shows the total time taken, with one or four threads active.
Operating System: Three Easy Pieces --- Lock Concurrent Data Structures (Note)
标签:
原文地址:http://www.cnblogs.com/miaoyong/p/4932054.html