首页 \ 问答 \ 为什么在ReentrantReadAndWriteLock中,readLock()应该在writeLock.lock()之前解锁?(Why in ReentrantReadWriteLock, should the readLock() be unlocked before writeLock().lock()?)

为什么在ReentrantReadAndWriteLock中,readLock()应该在writeLock.lock()之前解锁?(Why in ReentrantReadWriteLock, should the readLock() be unlocked before writeLock().lock()?)

ReentrantReadAndWriteLock类javadoc

void processCachedData() {
  rwl.readLock().lock();
  if (!cacheValid) {
     // Must release read lock before acquiring write lock
5:   rwl.readLock().unlock();
6:   rwl.writeLock().lock();
     // Recheck state because another thread might have acquired
     //   write lock and changed state before we did.
     if (!cacheValid) {
       data = ...
       cacheValid = true;
     }
     // Downgrade by acquiring read lock before releasing write lock
14:  rwl.readLock().lock();
15:  rwl.writeLock().unlock(); // Unlock write, still hold read
  }

  use(data);
  rwl.readLock().unlock();
}

为什么我们必须在获取写入锁之前释放读锁? 如果当前线程持有读锁定,则应允许在其他线程不再读取时获取写锁定,而不管当前线程是否也持有读锁定。 这是我期望的行为。 最终在第4和第5行锁定升级,并在第14和第15行锁定降级,我期望在ReentrantReadAndWriteLock类中进行内部完成。 为什么这是不可能的?

换句话说,我希望代码能够正常工作,如下所示:

void processCachedData() {
  rwl.readLock().lock();
  if (!cacheValid) {
     // The readlock is upgraded to writeLock when other threads 
     // release their readlocks.
     rwl.writeLock().lock();
     // no need to recheck: other threads can't have acquired  
     // the write lock since this thread still holds also the readLock!!!
     if (!cacheValid) {  
       data = ...
       cacheValid = true;
     }
     // Downgrade by acquiring read lock before releasing write lock
     rwl.writeLock().unlock(); // Unlock write, still hold read
  }

  use(data);
  rwl.readLock().unlock();
}

这看起来好多了,也是更安全的方式来处理锁定,不是吗?

有人可以解释为什么这个奇怪的实现? 谢谢。


From the ReentrantReadWriteLock class javadoc:

void processCachedData() {
  rwl.readLock().lock();
  if (!cacheValid) {
     // Must release read lock before acquiring write lock
5:   rwl.readLock().unlock();
6:   rwl.writeLock().lock();
     // Recheck state because another thread might have acquired
     //   write lock and changed state before we did.
     if (!cacheValid) {
       data = ...
       cacheValid = true;
     }
     // Downgrade by acquiring read lock before releasing write lock
14:  rwl.readLock().lock();
15:  rwl.writeLock().unlock(); // Unlock write, still hold read
  }

  use(data);
  rwl.readLock().unlock();
}

Why must we release the read lock before acquiring the write lock as written in the comment? If the current thread holds the read lock, then it should be allowed to acquire the write lock when other threads are not reading anymore, regardless of whether the current thread also holds the read lock. This is the behavior I would expect.

I would expect the lock upgrade at lines 5 and 6 and the lock downgrade at lines 14 and 15 to be done internally in the ReentrantReadWriteLock class. Why is that not possible?

In other words, I would expect the code to work fine like this:

void processCachedData() {
  rwl.readLock().lock();
  if (!cacheValid) {
     // The readlock is upgraded to writeLock when other threads 
     // release their readlocks.
     rwl.writeLock().lock();
     // no need to recheck: other threads can't have acquired  
     // the write lock since this thread still holds also the readLock!!!
     if (!cacheValid) {  
       data = ...
       cacheValid = true;
     }
     // Downgrade by acquiring read lock before releasing write lock
     rwl.writeLock().unlock(); // Unlock write, still hold read
  }

  use(data);
  rwl.readLock().unlock();
}

This looks like a much better and safer way to handle locking, doesn't it?

Can somebody explain the reason for this weird implementation? Thanks.


原文:https://stackoverflow.com/questions/16901640
更新时间:2023-10-15 22:10

最满意答案

您可以在完成后让用户标记。 ( 现场示例

numbers = [];
in_num = None

while (in_num != ""):
    in_num = input("Please enter a number (leave blank to finish): ")
    try:
        numbers.append(int(in_num))
    except:
        if in_num != "":
            print(in_num + " is not a number. Try again.")

# Calculate largest and smallest here.

您可以为“停止”选择任何字符串,只要它与in_num的初始值不同in_num

顺便说一句,您应该添加逻辑来处理错误的输入(即不是整数)以避免运行时异常。

在此特定示例中,您可能还想创建smallestlargest变量,并在每次输入后计算它们的值。 对于一个小的计算来说并不重要,但是当你转向更大的项目时,你会想要保持代码的效率。


You could let the user flag when they are finished. (live example)

numbers = [];
in_num = None

while (in_num != ""):
    in_num = input("Please enter a number (leave blank to finish): ")
    try:
        numbers.append(int(in_num))
    except:
        if in_num != "":
            print(in_num + " is not a number. Try again.")

# Calculate largest and smallest here.

You can choose any string you want for the "stop", as long as it's not the same as the initial value of in_num.

As an aside, you should add logic to handle bad input (i.e. not an integer) to avoid runtime exceptions.

In this specific example, you'd also probably want to create smallest and largest variables, and calculate their values after each input. Doesn't matter so much for a small calculation, but as you move to bigger projects, you'll want to keep the efficiency of the code in mind.

相关问答

更多
  • 查看textinput方法: def textinput(self, title, prompt): """Pop up a dialog window for input of a string. Arguments: title is the title of the dialog window, prompt is a text mostly describing what information to input. Return the string input ...
  • #!/usr/bin/python3是一个shebang行 。 shebang行定义了解释器所在的位置。 在这种情况下, python3解释器位于/usr/bin/python3 。 它可能是一个bash , ruby , perl或任何其他脚本语言的解释器。 如果您在脚本中设置执行标志并运行它,就像./script.py一样,操作系统不知道它是一个python脚本,除非你像python3 script.py一样运行或设置shebang行。 如果语言翻译器安装在不同的位置,您可以使用/usr/bin/env ...
  • 我不确定是否有更好的方法,但你可以用一行中的列表理解来做到这一点: val1, val2 = [float(item) for item in input("Enter two floating point values: ").split(",")] 您可以使用map函数执行的另一个选项: val1, val2 = map(float(input("Enter two floating point values: ").split(",")) 请注意,在Python 3.x中,第二个版本返回一个地图对 ...
  • 如文档中所述 然后该函数从输入中读取一行, 将其转换为字符串 (剥离尾部换行符),然后返回该行 因此,您需要将其float类型转换为float raio_bocal = float(input("Type de raingauge radius [cm]:")) As mentioned in the docs The function then reads a line from input, converts it to a string (stripping a trailing newline), ...
  • 您可以在完成后让用户标记。 ( 现场示例 ) numbers = []; in_num = None while (in_num != ""): in_num = input("Please enter a number (leave blank to finish): ") try: numbers.append(int(in_num)) except: if in_num != "": print(in_num + " i ...
  • 只需使用该键索引字典: dd[next(reversed(dd))] 例如: from collections import OrderedDict dd = OrderedDict(a=1, b=2) print(dd[next(reversed(dd))]) # 2 Just use that key to index the dictionary: dd[next(reversed(dd))] For example: from collections import OrderedDic ...
  • Pool.map使用os.listdir返回的每个名称重复调用worker函数。 在per_file_process , subject_files是单个文件名,而subject_files中的for pdf in subject_files:枚举名称中的各个字符。 此外, listdir仅显示基本名称,没有子目录,因此您没有在pdf的正确位置查找。 您可以使用glob按扩展名名称进行过滤,并返回文件的工作路径。 您的示例令人困惑... textExtractor()不带参数,那么如何知道它正在处理哪个文件 ...
  • 尝试: def get_plays(msg): while True: try: x = (int(input(msg))) if x <=0: print("Positive numbers only please.") continue if x not in range(20): print("Enter a n ...
  • 其中一个错误消息指出,libffi缺失。 在类似debian的系统上你可以试试$ sudo apt-get install libffi6 libffi-dev 。 one of the error messages states, that libffi is missing. on a debian-like system you could try $ sudo apt-get install libffi6 libffi-dev.
  • 可以这样做: x = int(input("Enter your number here: ")) def divide(x): for i in range(1,x): if i % 13 == 0: print (i) divide(x) Can do this: x = int(input("Enter your number here: ")) def divide(x): for i in range(1,x): if ...

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)