我希望python執行(類似於subprocess.Popen()
?)外部插座連接器後,我有另一個線程在socket.accept()
阻止。使一個線程中的「socket.accept」在另一個線程中的某個代碼之前執行? (python3)
import socket
import threading
import subprocess
host = '0.0.0.0'
port = 3333
def getsock():
server_sock = []
def getsock_server():
sock = socket.socket()
sock.bind((host, port))
sock.listen(1)
accept_return = sock.accept() # *** CRITICAL ACCEPT ***
server_sock.append(accept_return[0])
address = accept_return[1]
return address
thr = threading.Thread(target=getsock_server)
thr.start()
"""Something that *must* be done after the CRITICAL ACCEPT
line is executing and the thread "thr" is blocked. Otherwise
the program malfunctions and blows into some undebuggable
complexity. ;(
Although it is a connect operation, it may not be as innocent
as belowing lines:
client_sock = socket.socket()
client_sock.connect((host, port))
"""
p = subprocess.Popen(
["./connector"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
thr.join()
return server_sock[0]
conn, addr = getsock()
基本上,我需要的一切工作就像下面依次是:
1) thr.start()
2) sock.accept()
3) subprocess.Popen()
如果3)2前行),不良後果會怎樣。
沒有線程的解決方案(我認爲它首先肯定,因爲線程是麻煩..)是不可能的,因爲當我不能不打斷subprocess.Popen()
接受。
此外,我不想使用time.sleep(SOME_LARGE_VALUE)
,因爲它也是不可控制的(容易出錯,我使用正確的單詞嗎?),而且速度慢。
我已經瞭解到:Python3(CPython)具有全局解釋器鎖定(GIL)機制。有一次只有一個線程有執行的機會。如果一個線程阻塞(在本例中爲socket.accept()
),CPython將轉向另一個線程。 (但是,這並沒有幫助解決問題。)
任何人都知道強制執行命令的pythonic方式(或非pythonic方式)嗎?
「不良後果」?給我們一個提示怎麼樣?我可以看到想要在偵聽之後進行調用,但子進程中接受的地方應該在哪裏運行?在接受之前,在接受之後?爲什麼在子流程運行之前,accept會被阻塞? – tdelaney
一旦'listen(1)'返回,TCP堆棧將在後臺排隊多達1個連接請求,即使你還沒有調用accept。只要你在對方感到無聊並重置連接之前調用accept,它就會完成連接。 – tdelaney
我會試一試......看起來我對套接字系統調用很不熟悉......:P – Thiner