簡體   English   中英

Python多線程 - 主線程塊socket.connect

[英]Python multithreading - main thread block socket.connect

我有以下問題。 我的線程很少。 主要線程只等待終止調用和上傳文件的線程子節點。 不幸的是,當他們想要連接特定服務器時,子線程被阻止。 我在Linux上使用python2.7。

主線程包含以下代碼:

    for i in xrange(n):
        upl = UploaderThread(self.user, self.password)
        upl.start()
    while threading.active_count() > 1:
        time.sleep(1000.)

這是子線程掛起的片段

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(glob_timeout)
    #this fragment of code is accessed
    sock.connect( ("95.211.193.147", 8084 ) ) <- here the child-thread is blocked
    #this fragment of code is not accessed anymore
    sock.send(header)

我做錯了什么?


當我運行相同程序的幾個副本(每個副本是一個上傳線程)時一切正常。 這意味着服務器允許來自一個客戶端的多個連接。

當沒有主線程時,一切都有效,即當我以這種方式更改主線程時(刪除等待循環):

    for i in xrange(n):
        upl = UploaderThread(self.user, self.password)
        upl.start()

然后在主線程死亡后,每個子線程都工作(不再被阻塞)。

當我嘗試連接其他服務器(而不是“95.211.193.147”,8084)時,子線程不會阻止子線程。

我真的不明白發生了什么。


UploaderThread的定義

class UploaderThread(threading.Thread):
    def __init__(self, user, password):
        threading.Thread.__init__(self)
        self.uploader   = Uploader(user, password)
        self.daemon     = False

    def run(self):
        self.uploader.upload_dir()

和self.uploader.upload_dir()包含與服務器連接的代碼段。

您可能需要考慮使用多處理庫而不是線程。 它有一些局限性,但它避開了GIL問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM