线程与线程

发布于 2024-10-30 22:17:06 字数 70 浏览 1 评论 0原文

Python 中的 threadingthread 模块有什么区别?

What's the difference between the threading and thread modules in Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

演多会厌 2024-11-06 22:17:06

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

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

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

注意:正如Jeril的替代答案中提到的,当考虑在Python中使用线程来执行后台任务时,也采取将concurrent.futures.ThreadPoolExecutor视为比线程更高级别的API:https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor

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.

Note: as mentioned in Jeril's alternate answer, when considering the use of threads in Python for execution of background tasks, also take a look at concurrent.futures.ThreadPoolExecutor as an even higher level API than threading: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor

软甜啾 2024-11-06 22:17:06

threading 只是一个与thread 接口的更高级别模块。

请参阅此处的线程文档:

http://docs.python.org/library/threading。 html

threading is just a higher level module that interfaces thread.

See here for the threading docs:

http://docs.python.org/library/threading.html

因为看清所以看轻 2024-11-06 22:17:06

如果我没记错的话,线程允许您将函数作为单独的线程运行,而使用线程必须< /s> 创建一个,但获得更多功能。

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

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

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()
  • Create a child class of threading.Thread with your own run() method, and start it
当爱已成负担 2024-11-06 22:17:06

Python 中还有另一个库可以用于线程并且工作得很好。

该库名为 concurrent.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()

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()
顾挽 2024-11-06 22:17:06

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文