长话短说,在Python 3.2中,Antoine Pitrou 编写一个在单核和多核计算机上具有相同性能的新GIL .在以前的版本中,您拥有的内核/线程越多,性能损失就会增加...希望它会有所帮助:)Say I have a function that writes to a file. I also have a function that loops repeatedly reading from said file. I have both of these functions running in separate threads. (Actually I am reading/writing to registers via MDIO which is why I can't have both threads executing concurrently, only one or the other, but for the sake of simplicity, let's just say it's a file)Now when I run the write function in isolation, it executes fairly quickly. However when I'm running threaded and have it acquire a lock before running, it seems to run extremely slow. Is this because the second thread (read function) is polling to acquire the lock? Is there any way to get around this?I am currently just using a simple RLock, but am open to any change that would increase performance.Edit: As an example, I will put a basic example of what's going on. The read thread is basically always running, but occasionally a separate thread will make a call to load. If I benchmark by running load from cmd prompt, running in a thread is at least 3x slower.write thread: import usbmpc # functions I made which access dll functions for hardware, etcdef load(self, lock): lock.acquire() f = open('file.txt','r') data = f.readlines() for x in data: usbmpc.write(x) lock.release()read thread: import usbmpcdef read(self, lock): addr = START_ADDR while True: lock.acquire() data = usbmpc.read(addr) lock.release() addr += 4 if addr > BUF_SIZE: addr = START_ADDR 解决方案 Do you use threading on a multicore machine?If the answer is yes, then unless your Python version is 3.2+ you are going to suffer reduced performance when running threaded applications.David Beazly has put considerable effort to find what is going on with GIL on multicores and has made it easy for the rest of us to understand it too. Check his website and the resources there. Also you might want to see his presentation at PyCon 2010. It is rather intresting.To make a long story short, in Python 3.2, Antoine Pitrou wrote a new GIL that has the same performance on single and multicore machines. In previous versions, the more cores/threads you have, the performance loss increases...hope it helps :) 这篇关于Python:线程+锁定大大降低了我的应用程序运行速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!