如何在Python中使用线程?

如何在Python中使用线程?

我试图理解Python中的线程。我看过文档和示例,但坦率地说,很多例子都过于复杂,我很难理解它们。

你如何清楚地展示为多线程划分的任务?


SMILET
浏览 850回答 4
4回答

qq_花开花谢_0

注意:对于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中以串行方式执行,尽管是交错的(带有上下文切换的额外开销)。
打开App,查看更多内容
随时随地看视频慕课网APP