我希望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