查看: 1510|回复: 2

error: can't start new thread

[复制链接]

11

主题

63

帖子

159

积分

注册会员

Rank: 2

积分
159
发表于 2018-9-27 16:10:56 | 显示全部楼层 |阅读模式
我有一个网站配置是: Django + mod-wsgi + apache,我发送另一个HTTP请求到另一个服务,并通过python的httplib库解决这个问题。但是有时候这个服务不会得到太长的响应,httplib的超时也不起作用。所以我创建了一个线程,在这个线程中我向服务发送请求,并在20秒后加入它(20秒-请求超时)。它是这样工作的:
  1. class HttpGetTimeOut(threading.Thread):
  2.     def __init__(self,**kwargs):
  3.         self.config = kwargs
  4.         self.resp_data = None
  5.         self.exception = None
  6.         super(HttpGetTimeOut,self).__init__()
  7.     def run(self):

  8.         h = httplib.HTTPSConnection(self.config['server'])
  9.         h.connect()
  10.         sended_data = self.config['sended_data']
  11.         h.putrequest("POST", self.config['path'])
  12.         h.putheader("Content-Length", str(len(sended_data)))
  13.         h.putheader("Content-Type", 'text/xml; charset="utf-8"')
  14.         if 'base_auth' in self.config:
  15.             base64string = base64.encodestring('%s:%s' % self.config['base_auth'])[:-1]
  16.             h.putheader("Authorization", "Basic %s" % base64string)
  17.         h.endheaders()

  18.         try:
  19.             h.send(sended_data)
  20.             self.resp_data = h.getresponse()
  21.         except httplib.HTTPException,e:
  22.             self.exception = e
  23.         except Exception,e:
  24.             self.exception = e
  25. something like this...
  26. And use it by this function:
  27. getting = HttpGetTimeOut(**req_config)
  28. getting.start()
  29. getting.join(COOPERATION_TIMEOUT)
  30. if getting.isAlive(): #maybe need some block
  31.     getting._Thread__stop()
  32.     raise ValueError('Timeout')
  33. else:
  34.     if getting.resp_data:
  35.         r = getting.resp_data
  36.     else:
  37.         if getting.exception:
  38.             raise ValueError('REquest Exception')
  39.         else:
  40.             raise ValueError('Undefined exception')
复制代码

一切都正常运行,但有时发生这个错误
error: can't start new thread
at the line of starting new thread:
getting.start()
and the next and the final line of traceback is
File "/usr/lib/python2.5/threading.py", line 440, in start
    _start_new_thread(self.__bootstrap, ())
谁能告诉我如何解决吗?
回复

使用道具 举报

5

主题

41

帖子

108

积分

注册会员

Rank: 2

积分
108
发表于 2018-9-27 16:16:56 | 显示全部楼层
"can't start new thread" 错误是肯定的,因为你已经在python进程中运行了太多的线程,而且由于某种资源限制,创建新线程的请求被拒绝。您可能应该查看正在创建的线程的数量;您能够创建的最大数量将由您的环境决定,但至少应该是数百个。在这里重新考虑您的架构可能是个好主意;考虑到这是异步运行的,也许您可以使用线程池从另一个站点获取资源,而不是总是为每个请求启动一个线程。另一个需要考虑的改进是线程的使用。加入和Thread.stop;通过向HTTPSConnection的构造函数提供超时值,可能会更好地完成此任务。
回复

使用道具 举报

11

主题

80

帖子

199

积分

注册会员

Rank: 2

积分
199
发表于 2018-9-27 16:18:13 | 显示全部楼层
你启动的线程比系统能够处理的线程多。对于一个进程,可以激活的线程数量是有限制的。你的应用程序启动线程的速度要快于线程完成的速度。如果你需要启动多个线程,则需要以一种更受控制的方式来执行,我建议使用线程池。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表