线程与线程


Answers:


87

在Python 3中,thread已重命名为_thread。它是用于实现的基础结构代码,threading普通的Python代码不应该靠近它。

_thread公开了底层操作系统级别流程的原始视图。这几乎绝不是您想要的,因此在Py3k中重命名以表明它实际上只是实现细节。

threading 添加了一些额外的自动记帐功能,以及一些便捷实用程序,所有这些使它成为标准Python代码的首选。



11

如果我没记错的话,thread允许您将函数作为单独的线程运行,而threading必须创建一个class,但是要获得更多的功能。

编辑:这不是完全正确。threading模块提供了创建线程的不同方法:

  • threading.Thread(target=function_name).start()
  • threading.Thread使用您自己的run()方法创建的子类,然后启动它

-1

Python中还有一个库可以用于线程化,并且运行良好。

该库称为current.futures。这使我们的工作更加轻松。

它具有线程池进程池

以下提供了一个见解:

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()

-2

模块“线程”将线程视为函数,而模块“线程”以面向对象的方式实现,即每个线程都对应一个对象。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.