django 内使用 threading 模块导致程序启动即崩溃

2019-03-27 10:05:36 +08:00
 lasuar

使用 uwsgi 作为 web 服务器启动,配置 4 个 worker,启动 django 后服务无法正常访问,uwsgi 日志出现大量如下内容:
** uWSGI listen queue of socket "127.0.0.1:9001" (fd: 3) full !!! (101/100) **
** uWSGI listen queue of socket "127.0.0.1:9001" (fd: 3) full !!! (101/100) **
** uWSGI listen queue of socket "127.0.0.1:9001" (fd: 3) full !!! (101/100) **

场景:
某一个功能使用 threading 模块,伪代码如下:

    def _thread_mission():
        def _core():
            while True:
                <make a http request and do some logical work>
                time.sleep(10)

        t_lst = [threading.Thread(target=_core),
                 threading.Thread(target=_core_1),
                 threading.Thread(target=_core_2),
                 ]
        for t in t_lst:
            t.setDaemon(True)
            t.start()

三个线程任务的内容类似,都是一个 while 循环,不断的定时请求某一个 url 然后执行一些业务逻辑。
应该描述的差不多了,有么有经验的大佬分析一波呢?感谢~

append: 将这三个定时任务使用 crontab 执行就没有上面的报错了。

3297 次点击
所在节点    Django
12 条回复
nicevar
2019-03-27 10:18:16 +08:00
是不是线程生命周期结束了,线程里面还有代码没跑完,你把线程弄成全局控制的测试一下
lasuar
2019-03-27 10:19:41 +08:00
@nicevar 是死循环,不会结束的。
gulu
2019-03-27 10:26:51 +08:00
为什么出现这个原因不明白,但是楼上的提示是对的。t.setDaemon 可能不是你想的那样,set Daemon 后主线程退出则子线程立即退出
lasuar
2019-03-27 10:31:42 +08:00
手动 Append:4 个 worker,表示启动时有 12 个线程在单核并发,算上极端情况,uwsgi 定时并发向外发起 12 个 http 请求(请求的 url 没有问题不会导致超时,这个确认过),然后,这就导致崩溃吗?
lasuar
2019-03-27 10:35:50 +08:00
@gulu
@nicevar
当时的做法是全局启动的这个任务,且测试环境代码稳定运行几天,上线后不行,两个环境的唯一不同就是线上环境处理的请求量要多一些。
est
2019-03-27 10:38:01 +08:00
uWSGI 默认屏蔽 threading 的。。

最好就不要在 uWSGI 里用 thread

最好不要在 uwsgi 里用 thread

最好不要在 CPython 里用 thread
lasuar
2019-03-27 10:41:27 +08:00
@est 大佬你好,请问有相关参考文档或博客吗?
Vegetable
2019-03-27 10:59:41 +08:00
@lasuar

By default the Python plugin does not initialize the GIL. This means your app-generated threads will not run. If you need threads, remember to enable them with enable-threads. Running uWSGI in multithreading mode (with the threads options) will automatically enable threading support. This “ strange ” default behaviour is for performance reasons, no shame in that.


是这句?
https://uwsgi-docs.readthedocs.io/en/latest/ThingsToKnow.html
lasuar
2019-03-27 11:18:55 +08:00
@Vegetable 这句话说没有设置“ enable-threads ”项就不会执行启动的 thread,然后我测试环境是执行了的,同样的 uwsgi 配置。我的 uwsgi 配置有“ thread = 2 ”,没有配置 “ enable-threads ”。
Latin
2019-03-27 11:34:59 +08:00
上线程锁
est
2019-03-27 11:49:15 +08:00
@lasuar 这里的 thread=2 是每个进程可以通过 2 个线程去同时处理 http 请求。
est
2019-03-27 11:50:34 +08:00
@lasuar 如果你想在 uWSGI 把 thread 的行为调试出来跑起来很顺畅我是劝你。。早点放弃。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/548976

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX