Sometimes, we want to use threading in Python.
In this article, we’ll look at how to use threading in Python.
How to use threading in Python?
To use threading in Python, we can use the Pool
class from the multiprocessing.dummy
module.
For instance, we write:
import urllib.request
from multiprocessing.dummy import Pool as ThreadPool
urls = [
'http://www.python.org', 'http://www.python.org/about/',
'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
'http://www.python.org/doc/', 'http://www.python.org/getit/'
]
pool = ThreadPool(4)
results = pool.map(urllib.request.urlopen, urls)
pool.close()
pool.join()
We import the Pool
class as ThreadPool
.
Then we create a thread pool with 4 worker threads in it with the ThreadPool
class.
Next, we call pool.map
with the urllib.request.urlopen
function and urls
to call urllib.request.urlopen
with the entries in urls
and return the results.
Then we call pool.close
to close the pool and wait for the work to finish with pool.join
.
Conclusion
To use threading in Python, we can use the Pool
class from the multiprocessing.dummy
module.