12.1 启动与停止线程

问题

You want to create and destroy threads for concurrent execution of code.

解决方案

The threading library can be used to execute any Python callable in its own thread. Todo this, you create a Thread instance and supply the callable that you wish to executeas a target. Here is a simple example:

讨论

Due to a global interpreter lock (GIL), Python threads are restricted to an executionmodel that only allows one thread to execute in the interpreter at any given time. Forthis reason, Python threads should generally not be used for computationally intensivetasks where you are trying to achieve parallelism on multiple CPUs. They are muchbetter suited for I/O handling and handling concurrent execution in code that performsblocking operations (e.g., waiting for I/O, waiting for results from a database, etc.).Sometimes you will see threads defined via inheritance from the Thread class. Forexample:

from threading import Thread

class CountdownThread(Thread):def init(self, n):super().init()self.n = 0def run(self):
while self.n > 0:

print(‘T-minus", self.n)self.n -= 1time.sleep(5)

c = CountdownThread(5)c.start()

Although this works, it introduces an extra dependency between the code and thethreading library. That is, you can only use the resulting code in the context of threads,whereas the technique shown earlier involves writing code with no explicit dependencyon threading. By freeing your code of such dependencies, it becomes usable in othercontexts that may or may not involve threads. For instance, you might be able to executeyour code in a separate process using the multiprocessing module using code like this:

import multiprocessingc = CountdownTask(5)p = multiprocessing.Process(target=c.run)p.start()...

Again, this only works if the CountdownTask class has been written in a manner that isneutral to the actual means of concurrency (threads, processes, etc.).

文章导航