python - 我可以在单个 heroku (python) dyno 中运行多个线程吗?

标签 python multithreading heroku

在 heroku 上运行单个 dyno 时,threading 模块是否工作? 例如:

import threading
import time
import random


def foo(x, s):    
    time.sleep(s)
    print ("%s %s %s" % (threading.current_thread(), x, s))

for x in range(4):
    threading.Thread(target=foo, args=(x, random.random())).start()

应该返回类似...

$ python3 mythread.py
<Thread(Thread-3, started 123145318068224)> 2 0.27166873449907303
<Thread(Thread-4, started 123145323323392)> 3 0.5510182055055494
<Thread(Thread-1, started 123145307557888)> 0 0.642366815814484
<Thread(Thread-2, started 123145312813056)> 1 0.8985126103340428

是吗?

最佳答案

是的。这很好用 =) 刚刚在最新的 Python 3 版本上测试过。您可以自己在 Heroku 上轻松地对此进行测试。

Heroku dynos 使用虚拟 CPU 核心,但线程仍然可以正常工作。

编辑:这是我的 Heroku 日志

2016-08-02T20:18:35.040230+00:00 heroku[test.1]: State changed from starting to up
2016-08-02T20:18:36.871061+00:00 app[test.1]: <Thread(Thread-3, started 140472762279680)> 2 0.10491314677740204
2016-08-02T20:18:36.969173+00:00 app[test.1]: <Thread(Thread-1, started 140472795842304)> 0 0.2034461123977389
2016-08-02T20:18:37.117934+00:00 app[test.1]: <Thread(Thread-2, started 140472779060992)> 1 0.35186381754517004
2016-08-02T20:18:37.476239+00:00 app[test.1]: <Thread(Thread-4, started 140472542557952)> 3 0.7093646481085698

关于python - 我可以在单个 heroku (python) dyno 中运行多个线程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38632621/

相关文章:

python - 如何遍历嵌套的字典列表?

c++ - 如何使用带线程的套接字? c++ 与 ubuntu

c++ - 是否有可能检测到线程在 Linux [暂停] 中进行了上下文切换?

python - Django [Mezzanine CMS] 项目未部署到 Heroku

python - 如何在点击按钮时运行python脚本?

python - 如何指定 mypy 类型的 pytest_configure fixture ?

python - 如何将现有环境克隆到anaconda中的基础环境

java - 如何确定高延迟网络请求的最佳线程数?

amazon-web-services - 从Heroku发送电子邮件时,是否可以获得Amazon SES免费定价?

python - Heroku 上的 Django : relation "app_label" does not exist