[pyar] can't start new thread

Martin Chikilian slacklinucs en gmail.com
Lun Mayo 2 21:17:49 ART 2011


Gerardo,

Date una vueltita por

http://stackoverflow.com/questions/344203/maximum-number-of-threads-per-process-in-linux

Quizás es lo que te está pasando, estás abriendo demasiados procesos en tu
sistema.

Saludos,

Martín

On Mon, May 2, 2011 at 6:16 PM, Gerardo Herzig <gherzig en fmed.uba.ar> wrote:

> Hola chicos. Tengo una pequeña aplicacion que me esta tirando ese error.
>
> No logro dar pie con bola, aunque supongo que el asunto viene porque me
> esta faltando cerrar los threads, o algo relacionado.
>
> Este programin recorre los directorios, y por cada directorio abre un
> hilo por cada archivo que procesa (en particular, ahora esta seteado
> para procesar unicamente pdf's)
>
> En cada directorio hay a lo sumo 20 pdf's. Por eso supongo que la cosa
> viene por algo en la finalizacion de los threads:
>
> Se que el mail es muy largo, e incluso faltan algunas bibliotecas para
> que les funcione, pero me la juego a que lo puedan seguir a ojimetro, y
> me sepan tirar alguna papusa.
>
> Gracias chicos!
>
> Este es el prg principal:
>
> #! /usr/bin/python
> # -*- coding: UTF-8 -*-
>
> import defaultValues
> from threading import Thread
> from Queue import Queue
> import os
> import time
> import string
> from GAG3.Logger.Logger import Logger
> from ArchivoPDF import ArchivoPDF
> from ArchivoHTML import ArchivoHTML
>
> class ProcesaDirectorioConHilos(object):
>  _extensiones_validas = ['htm']
>  def __init__(self,dirname):
>  self.queue = Queue()
>  self.num_threads = 5
>  self.dirname = dirname
>  for archivo in [x for x in os.listdir(os.path.join(dirname)) if
>      os.path.isfile(os.path.join(dirname,x))]:
>   extension = string.lower(os.path.splitext(archivo)[-1][1:])
>   if extension in self._extensiones_validas:
>    self.queue.put(archivo)
>
>  def process(self):
>  for x in range(self.num_threads):
>   worker = Thread(target = processFile, args = (self.dirname,
> self.queue))
>
>   worker.setDaemon(True)
>   worker.start()
>   self.queue.join()
>
> def processFile(dir, q):
>  _extensiones_validas = ['htm']
>
>  while True:
>  if not q.empty():
>   archivo = q.get()
>   extension = string.lower(os.path.splitext(archivo)[-1][1:])
>   if extension in _extensiones_validas:
>
>    if extension == 'pdf':
>     f = ArchivoPDF(dir,archivo)
>    elif extension in ('html', 'htm'):
>     f = ArchivoHTML(dir, archivo)
>    else:
>     pass #Extension no soportada / implementada
>    try:
>     f.save()
>    except:
>     pass
>    finally:
>     q.task_done()
>
>
> La clasesita ArchivoHTML:
>
> import ArchivoBase
>
> class ArchivoHTML(ArchivoBase.ArchivoBase):
>
>  def process(self):
>    _body = self._file.readlines()
>    _body = ''.join([x.strip() for x in _body])
>    return _body
>
> Y la clase ArchivoBase:
>
> import defaultValues
> from GAG3.DbRequired.db import DB
> import os
> import time
>
> class ArchivoBase(object):
>  """
>  Clase base para todas los tipos de archivo soportados
>  """
>  def __init__(self,dirName, fileName):
>  self.root = '/mnt/'
>  self.fileName = fileName
>  self.path = u'%s'.encode("ascii", "ignore") % os.path.join(dirName,
> fileName)
>  self._file = open(self.path)
>  self.path_web = u'%s'.encode("ascii", "ignore") %
> os.path.join(dirName, fileName).replace(self.root,'/')
>  self.db = DB()
>  self.db.connect()
>  self.db.doQuery("set client_encoding to 'latin1'", None)
>
>  def process(self):
>  pass
>
>  def esNuevo(self):
>  ###Retorna True si el archivo en cuestion no aparece en la base
>
>  existe = self.db.doQuery("select page_id from gse_data where url='%s'"
> % self.path_web)
>  if not existe:
>   return True
>  else:
>   return False
>
>  def estaActualizado(self):
>  este = self.last_modified_timestamp()
>  try:
>   actual = self.db.doQuery("select last_modified_timestamp from
> gse_data where url='%s'" % self.path_web, [])[0][0]
>  except:
>   return True
>  if este > actual: #Hay que actualizar
>   return False
> else:
>   return True
>
>  def last_modified_timestamp(self):
>  return os.stat(self.path).st_mtime
>
>
>  def save(self):
>  try:
>   if self.esNuevo():
>    body = self.process()
>    self.db.doQuery("""insert into
> gse_data(url,body,last_modified_timestamp) values ('%s', $_$%s$_$,%d)"""
> % (self.path_web, body.strip(), self.last_modified_timestamp()), None)
>
>   else:
>    if not self.estaActualizado():
>     body = self.process()
>     self.db.doQuery("""update gse_data set body = $_$%s$_
> $,last_modified_timestamp = %d where url='%s'""" % (body.strip(),
> self.last_modified_timestamp(),self.path_web), None)
>
>   else: ## Ni es nuevo, ni esta desactualizado
>     _logger.info('%s up_to_date. Nada para hacer' % self.path)
>
>  finally:
>   self._file.close()
>   self.db.connection.close()
>   return
>
> _______________________________________________
> pyar mailing list pyar en python.org.ar
> http://listas.python.org.ar/listinfo/pyar
>
> PyAr - Python Argentina - Sitio web: http://www.python.org.ar/
>
------------ próxima parte ------------
Se ha borrado un adjunto en formato HTML...
URL: <http://listas.python.org.ar/pipermail/pyar/attachments/20110502/8ef74e08/attachment.html>


More information about the pyar mailing list