What\'s the difference between the threading
and thread
modules in Python?
If I'm not mistaken, thread
allows you to run a function as a separate thread, whereas with threading
you have to create a class, but get more functionality.
EDIT: This is not precisely correct. threading
module provides different ways of creating a thread:
threading.Thread(target=function_name).start()
threading.Thread
with your own run()
method, and start itthreading
is just a higher level module that interfaces thread
.
See here for the threading
docs:
http://docs.python.org/library/threading.html
There is another one library in Python which can used for threading and works perfectly.
The library called concurrent.futures. This makes our work easier.
It has for thread pooling and Process pooling.
The following gives an insight:
ThreadPoolExecutor Example
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout=timeout) as conn:
return conn.read()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
Another example
import concurrent.futures
import math
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419]
def is_prime(n):
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
def main():
with concurrent.futures.ThreadPoolExecutor() as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, prime))
if __name__ == '__main__':
main()
In Python 3, thread
has been renamed to _thread
. It is infrastructure code that is used to implement threading
, and normal Python code shouldn't be going anywhere near it.
_thread
exposes a fairly raw view of the underlying OS level processes. This is almost never what you want, hence the rename in Py3k to indicate that it is really just an implementation detail.
threading
adds some additional automatic accounting, as well as several convenience utilities, all of which makes it the preferred option for standard Python code.
The module "Thread" treats a thread as a function, while the module "threading" is implemented in an object oriented way, i.e. every thread corresponds to an object.