当我使用下面的代码时,使用单线程的时间是49.7秒,但是随着我增加线程的数量,如下所示
work1=TestThread(self,"worker1")
work2=TestThread(self,"worker2")
执行时间也在增加。在
^{pr2}$单线程的输出为:
Entering worker1
[<_MainThread(MainThread, started 9360)>, <Thread(SockThread, started daemon 4984)>, <TestThread(worker1, started 5776)>]
3
execution time of worker1 is: 49.2760000229
对于两个线程:
Entering worker1
Entering worker2
[<_MainThread(MainThread, started 8880)>, <Thread(SockThread, started daemon 8280)>, <TestThread(worker1, started 5788)>, <TestThread(worker2, started 12240)>]
4
execution time of worker2 is: 113.527999878
execution time of worker1 is: 114.292000055
为什么会这样。有人能解释吗?那是什么袜子线?TIA公司
由于Global Interpreter Lock,你的线程在同一个核心上相互竞争。全局解释器锁防止一次运行多个python线程,即使在多核系统上也是如此。因此,要并行执行多个cpu绑定的任务,必须使用进程(来自
multiprocessing
模块)而不是线程。在另外,列表中出现的
SockThread
是IDLE
的内部元素。在相关问题 更多 >
编程相关推荐