如何在python中使用线程来减少执行时间?

2024-10-01 13:41:25 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用下面的代码时,使用单线程的时间是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公司


Tags: ofselftimeis时间线程threadexecution
1条回答
网友
1楼 · 发布于 2024-10-01 13:41:25

由于Global Interpreter Lock,你的线程在同一个核心上相互竞争。全局解释器锁防止一次运行多个python线程,即使在多核系统上也是如此。因此,要并行执行多个cpu绑定的任务,必须使用进程(来自multiprocessing模块)而不是线程。在

另外,列表中出现的SockThreadIDLE的内部元素。在

相关问题 更多 >