我已经阅读了关于编写多线程代码时“糟糕”的Python GIL问题的很多内容,但是我从未看到过例子。请问有人可以给我一个基本的示例,说明在使用线程时GIL会引起什么问题。
谢谢!
我已经阅读了关于编写多线程代码时“糟糕”的Python GIL问题的很多内容,但是我从未看到过例子。请问有人可以给我一个基本的示例,说明在使用线程时GIL会引起什么问题。
谢谢!
import threading
import sys
import time
numSecondsToRun = 5
class CounterThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._counter = 0
self._endTime = time.time() + numSecondsToRun
def run(self):
# Simulate a computation on the CPU
while(time.time() < self._endTime):
self._counter += 1
if __name__ == "__main__":
if len(sys.argv) < 2:
print "Usage: python counter 5"
sys.exit(5)
numThreads = int(sys.argv[1])
print "Spawning %i counting threads for %i seconds..." % (numThreads, numSecondsToRun)
threads = []
for i in range(0,numThreads):
t = CounterThread()
t.start()
threads.append(t)
totalCounted = 0
for t in threads:
t.join()
totalCounted += t._counter
print "Total amount counted was %i" % totalCounted
以下是我在我的电脑上(一台启用了超线程的双核Mac Mini)得到的测试结果:
$ python counter.py 1
Spawning 1 counting threads for 5 seconds...
Total amount counted was 14210740
$ python counter.py 2
Spawning 2 counting threads for 5 seconds...
Total amount counted was 10398956
$ python counter.py 3
Spawning 3 counting threads for 5 seconds...
Total amount counted was 10588091
$ python counter.py 4
Spawning 4 counting threads for 5 seconds...
Total amount counted was 11091197
$ python counter.py 5
Spawning 5 counting threads for 5 seconds...
Total amount counted was 11130036
$ python counter.py 6
Spawning 6 counting threads for 5 seconds...
Total amount counted was 10771654
$ python counter.py 7
Spawning 7 counting threads for 5 seconds...
Total amount counted was 10464226