用threading 解决 gunicorn worker timeout

         产生worker timeout 的背景

        while 1:

              .....

              time.sleep(1)

       gunicorn运行起来,只等待了30s,就卡住了,没报任何异常或err,查了gunicorn 官方文档,原来是线程默认等待30s 就kill 掉,再restart

       http://docs.gunicorn.org/en/stable/settings.html

       

timeout

  • -t INT, --timeout INT
  • 30

Workers silent for more than this many seconds are killed and restarted.

Generally set to thirty seconds. Only set this noticeably higher if you’re sure of the repercussions for sync workers. For the non sync workers it just means that the worker process is still communicating and is not tied to the length of time required to handle a single request.

 

         根本原因找到了,在gunicorn启动加了--timeout  120 ,还是超过30s 就worker timeout.搜了一圈stack没发现好的解决方法。

        解决这个问题,目前最好的方法,就是在程序改代码,原先是主线程调用,用threading包装一下

        如:

         import threading

         t = threading.Thread(name = '', target = func ,kwargs{})

         t.daemon = True

         t.start()

         

          t = threading.Thread(name='result_package', target=result_package, args=(pack_name, task, issue))

   t.daemon = True
    t.start()

                 

           这样就在主线程下,把方法包装起来。

           顺便用

           Event().wait(15)  替代 time.sleep(16)

     这样写法的好处是不占用cpu,释放!

          

           刚开始,分析原因花了不少时间,几行代码就把worker timeout解决了。之前试了map.thread不行。

          准备用队列(celery+redis)替代原来的逻辑,只是工作量有点大,太重了。

            

在 Python 中,`threading` 模块提供了一种实现多线程编程的方式。在使用 `threading` 模块时,可以创建多个线程并行地执行不同的任务,从而提高程序的效率和响应速度。 `threading` 模块中的 `Thread` 类是创建线程的基本单元。创建一个线程需要定义一个函数并将其作为参数传递给 `Thread` 类的构造函数。这个函数被称为线程的 `worker` 函数。`worker` 函数是运行在一个单独的线程中的函数,可以执行任意的操作,包括计算、输入输出、网络通信等等。 下面是一个例子,演示了如何使用 `threading` 模块创建一个简单的线程,其中 `worker` 函数是一个简单的计数器: ```python import threading counter = 0 def worker(): global counter counter += 1 print('Worker count:', counter) threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start() ``` 在上面的代码中,我们首先定义了一个全局变量 `counter`,然后定义了一个 `worker` 函数,该函数会将 `counter` 的值加 1 并输出当前的计数器值。接下来,我们创建了 5 个线程,并让它们都运行 `worker` 函数。 在运行这个程序时,我们会看到输出的计数器值可能不是 1、2、3、4、5 这样的连续序列,而是一些随机的数字。这是因为多个线程同时对计数器进行了操作,而且这些操作之间是相互竞争的,所以最终的结果是不确定的。这也是多线程编程需要特别注意的地方之一。 总的来说,`worker` 函数是在一个单独的线程中运行的函数,可以执行任意的操作。在实际应用中,我们需要根据具体的需求来编写 `worker` 函数,从而实现多线程编程的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值