【问题标题】:Diving the same task into threads(processes?) in python在 python 中将相同的任务放入线程(进程?)
【发布时间】:2018-07-02 05:03:08
【问题描述】:

基本上我有一个函数,它可以从在线 ping 网络服务中获取 X 数量的(真实)随机数。然而,它相当慢,因为它会等待一个请求完成后再进行下一个请求。我将如何在其中添加多线程(或进程?),以便同时发送和打印多个请求。 (这些顺序不重要)

Python 有能力做到这一点吗?如果有怎么办?

谢谢

【问题讨论】:

标签: python multithreading python-3.x parallel-processing


【解决方案1】:

是的。这可以在 Python 中完成。 gevents 是我的 goto 库,用于与 Python 中的多线程或多处理相关的任何内容。

一个简单的例子是:

import gevent
from gevent import Greenlet

def foo(message, n):
    """
    Each thread will be passed the message, and n arguments
    in its initialization.
    """
    gevent.sleep(n)
    print(message)

# Initialize a new Greenlet instance running the named function
# foo
thread1 = Greenlet.spawn(foo, "Hello", 1)

# Wrapper for creating and runing a new Greenlet from the named
# function foo, with the passed arguments
thread2 = gevent.spawn(foo, "I live!", 2)

# Lambda expressions
thread3 = gevent.spawn(lambda x: (x+1), 2)

threads = [thread1, thread2, thread3]

# Block until all threads complete.
gevent.joinall(threads)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2012-12-13
    • 2012-04-05
    • 2016-09-09
    相关资源
    最近更新 更多