我希望 python 在 socket.accept()
处阻塞另一个线程之后执行(类似于 subprocess.Popen()
?)外部套接字连接器。
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),就会发生不良后果。
没有线程的解决方案(我首先肯定是这样,因为线程很麻烦..)是不可能的,因为当我 socket.accept()
我不能只是 subprocess.Popen()
不中断接受。
另外,我不想使用 time.sleep(SOME_LARGE_VALUE)
因为它也是不可控的(容易出现错误,我使用的词是否正确?)而且速度很慢。
我了解到:Python3(CPython)具有全局解释器锁(GIL)机制。同一时刻只有一个线程有执行的机会。如果一个线程阻塞(在本例中为 socket.accept()
),CPython 将转向另一个线程。 (但是,这并不能解决问题..)
有人知道执行命令的 Python 方式(或不那么 Python 方式)吗?
最佳答案
listen
告诉网络堆栈开始在后台对传入连接请求进行排队。每次调用 accept
都会接受队列中的下一个请求。看起来您的子进程想要连接回该程序。听完后调用即可。
import socket
import threading
import subprocess
host = '0.0.0.0'
port = 3333
def getsock():
server_sock = []
sock = socket.socket()
sock.bind((host, port))
sock.listen(1)
p = subprocess.Popen(
["./connector"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
return sock.accept() # *** CRITICAL ACCEPT ***
conn, addr = getsock()
关于python - 让一个线程中的 "socket.accept"在另一个线程中的某些代码之前执行? (python3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44615938/