问题
I am writing a python program that sends packets for a specified amount of time.
The sending script:
import socket
import time
import networkparam
import ray
ray.init()
transformer_sending_time = 0
final_message_sent = False
@ray.remote
def send_message():
"""
Sends an abnormal measurement to the specified ip address or port number given by the networkparam module
Parameters
----------
None, however we can consider the definitions in networkparam as the function args
Returns
----------
None
"""
global transformer_sending_time
global final_message_sent
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = networkparam.ip
port = networkparam.controller_port
message = b"bait"
seconds = 15
end_time = time.time() + seconds
while time.time() < end_time:
sock.sendto(message, (ip, port))
transformer_sending_time = time.time()
print("done")
final_message_sent = True
s = send_message.remote()
The receiving script:
import time
import socket
import networkparam
ip = networkparam.ip
controller_port = networkparam.controller_port
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((ip,controller_port))
while True:
data, addr = sock.recvfrom(1024)
if not data:
break
print("received message: %s" % data)
I am expecting the sending script to run for the full 15 seconds and "done" to be printed. However, the sending script sends packets for approximately 2 seconds and then breaks out of the function and "done" never gets printed.
回答1:
ray.remote
is a non-blocking operation. What's happening is your program is beginning the remote function call, then finishing. When it finishes, it tears down the ray cluster and ends the remote function.
You should add
s = send_message.remote()
ray.get(s)
The ray.get
will try to get the return value of send_message
(and return it), which means the program will have to wait for the remote function to finish.
来源:https://stackoverflow.com/questions/63539577/script-breaks-out-of-function-after-sending-a-few-packets