Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Ngay sau khi tất cả các độc giả phát hành khóa của họ thông qua một cuộc gọi đến ReleaseReaderLock (), nhà văn trong trường hợp này, chủ đề B-được cho phép để nhập khóa Chủ sở hữu khu vực. | CHAPTER 14 THREADING 321 As soon as all of the readers release their lock via a call to ReleaseReaderLock the writer in this case Thread B is allowed to enter the Lock Owners region. But what happens if Thread A releases its reader lock and then attempts to reacquire the reader lock before the writer has had a chance to acquire the lock If Thread A were allowed to reacquire the lock then any thread waiting in the writer queue could potentially be starved of any time with the lock. In order to avoid this any thread that attempts to require the read lock while a writer is in the queue is placed into the reader queue as shown in Figure 14-4. Figure 14-4. Reader attempting to reacquire lock Naturally this scheme gives preference to the writer queue. That makes sense given the fact that you d want readers to get the most up-to-date information. Of course had the thread that needs the writer lock called AcquireWriterLock while the ReaderWriterLock was in the state shown in Figure 14-2 it would have been placed immediately into the Lock Owners category without having to go through the writer queue. The ReaderWriterLock is reentrant. Therefore a thread can call any one of the lockacquisition methods multiple times as long as it calls the matching release method the same amount of times. Each time the lock is reacquired an internal lock count is incremented. It should seem obvious that a single thread cannot own both the reader and the writer lock at the same time nor can it wait in both queues in the ReaderWriterLock. It is possible however for a thread to upgrade or downgrade the type of lock it owns. For example if a thread currently owns a reader lock and calls UpgradeToWriterLock its read lock is released no matter what the lock count is and then it is placed into the writer queue. The UpgradeToWriterLock returns an object of type LockCookie. You should hold onto this object and pass it to DowngradeFromWriterLock when you re done with the write operation. The .