Last active
August 29, 2015 14:07
-
-
Save JuniorPolegato/2ccca44e322e8e3c3981 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import threading | |
import time | |
import sys,os | |
import subprocess | |
# Máximo de conexões/threads simultâneas | |
MAX_CONEXOES = 30 | |
# Bloco de linhas para processar | |
BLOCO = 300 | |
# Global | |
lista_threads = [] | |
# Função para imprimir uma linha por vez via lock | |
print_lock = threading.Lock() | |
def mostrar_msg(msg): | |
print_lock.acquire() | |
print msg | |
print_lock.release() | |
# Função para cada thread | |
def funcao_thread(lista_telefones): | |
mostrar_msg(lista_telefones) | |
# Função para iniciar uma thread esperando que uma outra termine caso | |
# tenha atingindo o máximo de threads/conexões | |
def iniciar_thread(telefones): | |
global lista_threads | |
while threading.active_count() > MAX_CONEXOES: | |
mostrar_msg("Esperando 1s para iniciar outra thread...") | |
time.sleep(1) | |
thread = threading.Thread(target=funcao_thread, args=(telefones,)) | |
lista_threads.append(thread) | |
thread.start() | |
# Thread principal | |
telefones = [] | |
with open('telefones.txt', 'rb') as arquivo: | |
for linha in arquivo: | |
telefones.append(linha.strip()) | |
if len(telefones) = BLOCO: | |
iniciar_thread(telefones) | |
telefones = [] | |
# No caso de ainda ter linhas para processar | |
if telefones: | |
iniciar_thread(telefones) | |
# Esperando pelas threads abertas terminarem | |
mostrar_msg("Esperando threads abertas terminarem...") | |
for thread in lista_threads: | |
thread.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment