Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

What I know is:

  • ReadLock and WriteLock affect each other somehow
  • WriteLock is just like synchronized
  • ReadLock seems cannot work alone
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
287 views
Welcome To Ask or Share your Answers For Others

1 Answer

readLock.lock();

  • This means that if any other thread is writing (i.e. holds a write lock) then stop here until no other thread is writing.
  • Once the lock is granted no other thread will be allowed to write (i.e. take a write lock) until the lock is released.

writeLock.lock();

  • This means that if any other thread is reading or writing, stop here and wait until no other thread is reading or writing.
  • Once the lock is granted, no other thread will be allowed to read or write (i.e. take a read or write lock) until the lock is released.

Combining these you can arrange for only one thread at a time to have write access, but as many readers as you like can read at the same time except when a thread is writing.

Put another way. Every time you want to read from the structure, take a read lock. Every time you want to write, take a write lock. This way whenever a write happens no-one is reading (you can imagine you have exclusive access), but there can be many readers reading at the same time so long as no-one is writing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...