2010-11-17 13 views
7

Come il seguente, mi piacerebbe comunicare con molti PC in un intervallo IP specifico.python socket.connect errore di timeout in multithread o multiprocesso

My PC ---+------> Client A PC 
     +------> Client B PC 
     +------> Client C PC 
     ................. 
     +------> Client Z PC 

Perché ci sono troppi client per comunicare, l'ho provato con il mulit-threading. socket.connect() produce continuamente errori di timeout. Se lo provo in un thread singolo, non ci sono problemi.

googled e trovato qui sotto:

Python Interpreter blocks Multithreaded DNS requests?

dicendo che in qualche piattaforma, modulo socket potrebbe essere pericoloso filo.

Così ho cambiato il mio codice in multielaborazione. Tuttavia produce ancora lo stesso errore.

Nel seguente esempio di codice, test_single() termina normale. test_mp() e test_mt() fanno entrambi errori di timeout.

Hai mai sperimentato un comportamento così anomalo? L'ambiente di test è Windows XP SP3, python 2.5.4. Anche provato su python 2.6.6 e 2.7.0, stesso errore.

import multiprocessing 
import Queue 
import socket 
import threading 

PROCESS_NUM = 5 
PORT = 8888 

def search_proc(ip): 
    try: 
     csock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
     csock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
     csock.settimeout(5.0) 
     csock.connect((ip, PORT)) 
     csock.shutdown(socket.SHUT_RDWR) 
     csock.close() 
     return ip, "ok" 
    except socket.error, msg: 
     return ip, "fail", msg 

def mp_connect(ip_range): 
    pool = multiprocessing.Pool(PROCESS_NUM) 
    for output in pool.imap_unordered(search_proc, ip_range): 
     print output 

def test_mp(): 
    ip_range = [] 
    for i in range(256): 
     ip_range.append("192.168.123.%d"%(i,)) 

    mp_connect(ip_range) 

def test_mt(): 
    def search_thread(ip_queue): 
     while True: 
      ip = ip_queue.get() 
      print search_proc(ip) 
      ip_queue.task_done() 
    ip_queue = Queue.Queue() 

    for i in range(256): 
     ip_queue.put("192.168.123.%d"%(i,)) 

    for i in range(PROCESS_NUM): 
     th = threading.Thread(target=search_thread, args=(ip_queue,)) 
     th.setDaemon(True) 
     th.start() 

    ip_queue.join() 

def test_single(): 
    ip_range = [] 
    for i in range(256): 
     print search_proc("192.168.123.%d"%(i,)) 

if __name__ == "__main__": 
    multiprocessing.freeze_support() 
    test_mp() 
    #test_single() 
    #test_mt() 

risposta

5

David Beazley ha svolto alcune ricerche su Python GIL e su come questo influisce su IO e sul multithreading. È possibile trovare informazioni sulla sua ricerca here, here.