为什么在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
最满意答案
您可以在完成后让用户标记。 ( 现场示例 )
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
。顺便说一句,您应该添加逻辑来处理错误的输入(即不是整数)以避免运行时异常。
在此特定示例中,您可能还想创建
smallest
和largest
变量,并在每次输入后计算它们的值。 对于一个小的计算来说并不重要,但是当你转向更大的项目时,你会想要保持代码的效率。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
andlargest
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 ...
-
Python3 - 多个输入(Python3 - Multiple inputs)[2023-10-27]
我不确定是否有更好的方法,但你可以用一行中的列表理解来做到这一点: 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 ...
-
Python3多处理(Python3 multiprocessing)[2022-03-05]
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 ...
-
Python3无法安装bcrypt(Python3 can't install bcrypt)[2022-10-23]
其中一个错误消息指出,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 ...