0

I'm currently dealing with an issue involving a list of threads who all use ssh/telnet libs. I want at some timeout value for the main thread to instruct the threads to close all their resources, and self-terminate. Here's an example of what my code looks like

import threading
import time
import socket

threads = []

def do_this(data):
    """this function is not the implementation this code may not be valid"""
    w = socket.create_connection(data, 100)
    while True:
        if 'admin' in w.read(256):
            break
    w.close

for data in data_list:
    t = threading.Thread(target=do_this, args=(data,))
    t.start()
    threads.append(t)

end_time = time.time()+120

for t in threads:
    t.join(end_time-time.time())

What I would like to do is have some way to signal the threads and modify the thread method so that it does something like this

def do_this(data):
    w = socket.create_connection(data, 100)
    while True:
        if 'admin' in w.read(256):
            break
    w.close()

    on signal:
        w.close()
        return
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
  • Just to be clear, in your second close block, you want ```on signal``` to kill the threads? – wnnmaw Jan 14 '14 at 18:17

1 Answers1

0

On UNIX you can use the following answer : Timeout function if it takes too long to finish

On Windows, it's a bit more tricky, since ther is no signal lib. Anyway, you just need a watchdog, so the timeout does not have to be precise :

def timeout(timeout):
    sleep(XX_SECONDS)
    timeout = True

def do_this(data):
    """this function is not the implementation this code may not be valid"""
    timeout = False
    w = socket.create_connection(data, 100)
    timer = threading.Thread( target = timeout, args=(timeout,) )
    while not timeout:
        if 'admin' in w.read(256):
            break

Alternatively, if you are using the socket lib, there is an option for them to be non-blocking : http://docs.python.org/2/library/socket.html#socket.socket.settimeout

Community
  • 1
  • 1
lucasg
  • 10,734
  • 4
  • 35
  • 57