为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Python中使用线程?

如何在Python中使用线程?

SMILET 2019-05-29 16:02:47
如何在Python中使用线程?我试图理解Python中的线程。我看过文档和示例,但坦率地说,很多例子都过于复杂,我很难理解它们。你如何清楚地展示为多线程划分的任务?
查看完整描述

4 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超6个赞

注意:对于Python中的实际并行化,您应该使用多处理模块来并行执行并行执行的多个进程(由于全局解释器锁定,Python线程提供交错但实际上是串行执行,而不是并行执行,并且仅在交错I / O操作)。

但是,如果您只是在寻找交错(或者正在进行可以并行化的I / O操作,尽管全局解释器锁定),那么线程模块就是起点。作为一个非常简单的例子,让我们通过并行求和子范围来考虑求和大范围的问题:

import threadingclass SummingThread(threading.Thread):
     def __init__(self,low,high):
         super(SummingThread, self).__init__()
         self.low=low
         self.high=high
         self.total=0

     def run(self):
         for i in range(self.low,self.high):
             self.total+=i


thread1 = SummingThread(0,500000)thread2 = SummingThread(500000,1000000)thread1.start() # This actually causes the thread to runthread2
.start()thread1.join()  # This waits until the thread has completedthread2.join()  # At this point, both threads have completedresult =
thread1.total + thread2.totalprint result

请注意,上面是一个非常愚蠢的例子,因为它绝对没有I / O,并且由于全局解释器锁,它将在CPython中以串行方式执行,尽管是交错的(带有上下文切换的额外开销)。


查看完整回答
反对 回复 2019-05-29
  • 4 回答
  • 0 关注
  • 843 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信