Python中的threading
和thread
模块有什么区别?
在Python 3中,thread
已更名为_thread
。它是用于实现threading
的基础结构代码,普通的Python代码不应该靠近它。
_thread
公开了底层操作系统级别进程的原始视图。这几乎不是你想要的,因此在Py3k中重命名表明它实际上只是一个实现细节。
threading
增加了一些额外的自动记帐功能,以及一些便利实用程序,所有这些都使它成为标准Python代码的首选选项。
如果我没有弄错的话,thread
允许你将一个函数作为一个单独的线程运行,而使用threading
你
不得不
创建一个类,但获得更多功能。
编辑:这不完全正确。 threading
模块提供了创建线程的不同方法:
threading.Thread(target=function_name).start()
threading.Thread
方法创建一个run()
子类,然后启动它Python中还有一个可以用于线程并且工作完美的库。
该图书馆名为concurrent.futures。这使我们的工作更轻松。
它有thread pooling和Process pooling。
以下是一个见解:
ThreadPoolExecutor示例
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)))
另一个例子
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()
模块“Thread”将线程视为函数,而模块“线程”以面向对象的方式实现,即每个线程对应一个对象。