标签: python-multithreading

Python 中的线程需要更长的时间而不是使其更快?

我编写了 3 个不同的代码来比较有线程和没有线程。基本上测量通过使用线程节省了多少时间,结果没有任何意义。

这是我的代码:

 import time



def Function():

    global x 
    x = 0

    while x < 300000000:
        x += 1
    print x

e1 = time.clock()
E1 = time.time()

Function() 

e2 = time.clock()
E2 = time.time()

print e2 - e1
print E2 - E1 
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到以下输出:

26.6358742929

26.6440000534
Run Code Online (Sandbox Code Playgroud)

然后我编写了另一个函数,如下所示,将计数到 3 亿拆分为计数 3、1 亿:

 import time




def Function():

    global x 
    x = 0

    while x < 100000000:
        x += 1
    print x

def Function2():

    global x 
    x = 0

    while x < 100000000: …
Run Code Online (Sandbox Code Playgroud)

python time multithreading python-multithreading python-multiprocessing

4
推荐指数
1
解决办法
6203
查看次数

线程脚本不打印到控制台

这真的让我很困惑,我找不到答案。

import thread
import time
import random
import sys 

sys.stdout.flush()

def run_often(thread_name, sleep_time):
    while True:
        time.sleep(sleep_time)
        print "%s" % (thread_name)
def run_randomly(thread_name, sleep_time):
    while True:
        time.sleep(sleep_time)
        print "%s" % (thread_name)

thread.start_new_thread(run_often,("Often runs", 2)) 
thread.start_new_thread(run_randomly, ("Fast and random", random.random()))
Run Code Online (Sandbox Code Playgroud)

问题是这不打印。在终端中,我输入 python threading.py (这是文件名),并且没有输出错误。所以代码可以编译,但只是不打印。换句话说,发生的事情是这样的:

$ python threading.py
$ 
Run Code Online (Sandbox Code Playgroud)

我添加了 sys.stdout.flush() 认为 stdout 需要重置,但无济于事。当我在任何函数的 while 循环之外添加一个随机打印语句(例如“hello world”)时,它会被打印出来。另外,当我在 ipython 中运行完全相同的代码时,它打印得非常完美。这是从 YouTube 教程复制的,不是我自己的代码。

关于为什么不打印的任何想法?我运行的Python是2.7.8。提前致谢。

python stdout python-multithreading

4
推荐指数
1
解决办法
1万
查看次数

Pandas、Concurrent.Futures 和 GIL

我正在 intel i3(四核)上使用 Pandas 0.18/Python 3.5 编写代码。

我读过这个: https: //www.continuum.io/content/pandas-releasing-gil

我还有一些 IO 绑定的工作(将 CSV 文件解析为数据帧)。我必须进行大量计算,其中大部分是乘以数据帧。

我的代码目前是并行使用的concurrent.futures ThreadPoolExecutor。

我的问题是:

  • 一般来说,我应该使用线程并行运行 pandas 作业,还是 pandas 是否有效地利用所有核心而无需我明确告诉它?(在这种情况下,我将连续执行我的工作)。

python multithreading python-multithreading pandas

4
推荐指数
1
解决办法
3458
查看次数

如何在Python中使用concurrent.futures

我正在努力让多线程在 Python 中工作。我有一个函数,我想根据一个参数在 5 个线程上执行。我还需要每个线程都相同的 2 个参数。这就是我所拥有的:

from concurrent.futures import ThreadPoolExecutor

def do_something_parallel(sameValue1, sameValue2, differentValue):
    print(str(sameValue1))        #same everytime
    print(str(sameValue2))        #same everytime
    print(str(differentValue))    #different

main(): 

    differentValues = ["1000ms", "100ms", "10ms", "20ms", "50ms"]

    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = [executor.submit(do_something_parallel, sameValue1, sameValue2, differentValue) for differentValue in differentValues]
Run Code Online (Sandbox Code Playgroud)

但我不知道下一步该做什么

python multithreading python-multithreading python-3.x concurrent.futures

4
推荐指数
1
解决办法
7436
查看次数

使用 Flask 路径启动和停止方法 (Python)

我正在使用 Flask 和 python(版本 3.6)构建一个小型实用程序。

该实用程序基本上使用 REST 调用来调用外部系统(sys1 和 sys2),并将数据从 sys1 单向同步到 sys2。该同步过程将持续运行,直到设置终止标志。

我希望能够使用烧瓶路线启动和停止此同步过程/方法。

例如,

  • 如果在 /start 处接收到请求,
    则 o 然后启动然后启动此方法。
    o 返回 HTTP 响应代码(响应不应等待方法完成)

  • 如果在 /stop 收到请求, o 如果该方法正在运行,则通过设置终止标志来停止该方法。 (再次强调,来自烧瓶的响应不应等待方法完成)

现在,我浏览了这里和其他网站的许多查询,但它们似乎都满足了特定的需求。根据我的理解,我尝试了以下方法(可能不正确地完成此任务:

  1. 尝试从路由创建一个线程并调用该方法 - 不起作用,因为由于某种原因 Flask 等待该方法完成(是因为 Flask 是单线程并且阻塞的吗?)

  2. 阅读有关芹菜的内容,但我觉得在这种情况下使用芹菜可能有点过分了。

异步启动此过程的正确方法是什么?如何?线程?asyncio 或 Celery 是唯一的方法。

celery python-multithreading flask python-3.x

4
推荐指数
1
解决办法
3660
查看次数

线程结束后释放内存

我正在开发一个主要是 API 的应用程序,但也有一个多线程后台作业处理系统,用于执行计划作业以及即时 API 响应时间过长的临时作业。

这将通过gunicorn分叉10次。任何单个分叉进程都能够选择要运行的作业,因此作业处理在进程之间与 API 请求服务之间保持平衡。

我的挑战是每个进程如何继续获取作业处理所需的峰值内存量。有些作业需要 1.5GB-2GB 的内存。

如果有足够的时间,最终所有 10 个进程都必须完成这些类型的工作,并且每个进程都将占用 2GB 以上的内存。即使进程的平均内存使用很少超过100MB。

这些密集型作业仅通过进程内的专用线程运行。

是否有任何机制可以强制Python在线程关闭时释放专门为该线程声明的内存?或者有什么通用机制可以强制 Python 进程将内存重置为当时真正需要的内存?

旁注:我也在探索分叉而不是线程,但到目前为止,这引入了其他问题,我不确定我是否可以解决。

python memory python-multithreading python-3.x

4
推荐指数
1
解决办法
1万
查看次数

从 python 中运行交互式程序

我想实现与此非常相似的目标。

\n\n

我的实际目标是从 python 中运行 Rasa。\n取自 Rasa\ 的站点:

\n\n
\n

Rasa 是一个用于构建会话软件的框架:Messenger/Slack 机器人、Alexa 技能等。我们\xe2\x80\x99ll 在本文档中将其缩写为机器人。

\n
\n\n

它基本上是一个在命令提示符下运行的聊天机器人。这就是它在 cmd 上的工作方式:\n在此输入图像描述

\n\n

现在我想从 python 运行 Rasa,以便可以将其与基于 Django 的网站集成。即我想继续从用户那里获取输入,将其传递给rasa,rasa处理文本并给我一个输出,然后将其显示给用户。

\n\n

我已经尝试过这个(到目前为止从cmd运行它)

\n\n
import sys\nimport subprocess\nfrom threading import Thread\nfrom queue import Queue, Empty  # python 3.x\n\n\ndef enqueue_output(out, queue):\n    for line in iter(out.readline, b\'\'):\n        queue.put(line)\n    out.close()\n\n\ndef getOutput(outQueue):\n    outStr = \'\'\n    try:\n        while True: #Adds output from the Queue until it is empty\n            outStr+=outQueue.get_nowait()\n    except Empty:\n        return outStr\n\np = subprocess.Popen(\'command_to_run_rasa\', \n                    stdin=subprocess.PIPE, \n …
Run Code Online (Sandbox Code Playgroud)

python subprocess python-multithreading rasa-nlu

4
推荐指数
1
解决办法
7135
查看次数

多处理池映射:AttributeError:无法腌制本地对象

我有一个与Python Multiprocessing Pool Map非常相似的问题 :AttributeError: Can't pickle local object

我想我明白问题出在哪里,我只是不知道如何解决它。“Pool.map”需要一个顶级函数作为输入。但我不知道如何重写这个问题:

一个简化的代码版本:

import os as os
from multiprocessing import Pool
import numpy as np
def opti_fun_data(prediction):
    def opti_fun(x):
        def error_fun(i):
            return error_fun_opti(x,prediction,i)
        try:
            pool = Pool(np.max([os.cpu_count()-1,1]))
            error = np.mean(pool.map(error_fun, range(M)))
        finally: # To make sure processes are closed in the end, even if errors happen
            pool.close()
            pool.join()
        return error
    return opti_fun

Run Code Online (Sandbox Code Playgroud)

如果我跑 opti_fun_data(prediction)(x0) 我得到

Can't pickle local object 'opti_fun_data.<locals>.opti_fun.<locals>.error_fun'

我是多处理库的新手,可以伸出援助之手。对于那些对一些背景感兴趣的人:我想为一堆不同的场景/预测最小化函数“opti_fun”。计算我的错误度量/基准(“error_fun_opti”)是安静的计算密集型,因此我尝试并行化这一步。

python mathematical-optimization multiprocessing python-multithreading python-multiprocessing

4
推荐指数
1
解决办法
4984
查看次数

线程未与 ThreadPoolExecutor 并行执行 python

我是 python 线程的新手,我正在试验这个:当我在线程中运行某些东西时(每当我打印输出时),它似乎永远不会并行运行。此外,我的函数花费的时间与使用库 concurrent.futures (ThreadPoolExecutor) 之前相同。我必须计算数据集上某些属性的增益(我不能使用库)。由于我有大约 1024 个属性并且该函数需要大约一分钟来执行(并且我必须在迭代中使用它)我决定将 的数组attributes分成 10 个(仅作为示例)并gain(attribute)单独运行 separete 函数每个子数组。所以我做了以下(避免一些额外的不必要的代码):

def calculate_gains(self):
    splited_attributes = np.array_split(self.attributes, 10)
    result = {}
    for atts in splited_attributes:
        with concurrent.futures.ThreadPoolExecutor() as executor:
            future = executor.submit(self.calculate_gains_helper, atts)
            return_value = future.result()
            self.gains = {**self.gains, **return_value}
Run Code Online (Sandbox Code Playgroud)

这是calculate_gains_helper:

def calculate_gains_helper(self, attributes):
    inter_result = {}
    for attribute in attributes:
        inter_result[attribute] = self.gain(attribute)
    return inter_result
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?我阅读了其他一些较旧的帖子,但无法获得任何信息。非常感谢您的帮助!

python concurrency machine-learning python-multithreading

4
推荐指数
2
解决办法
2286
查看次数

多线程请求 Python3

我对这个主题进行了大量研究,但问题是无法弄清楚如何使用 python3 发送多线程发布请求

names = ["dfg","dddfg","qwed"]

for name in names :
    res = requests.post(url,data=name)
    res.text 

Run Code Online (Sandbox Code Playgroud)

在这里,我想发送所有这些名称,并且我想使用多线程来使其更快。

multithreading python-multithreading python-3.x python-requests

4
推荐指数
1
解决办法
7767
查看次数