Concurrent service clients in ROS 2
I want to run 2 client to service Sum1
and Sum2
at the same time. I had tried MultiThreadedExecutor
but they are running sequentially. Below is my code:
class Test_client(Node):
def __init__(self,sv):
super().__init__(sv)
self.name = sv
self.group = ReentrantCallbackGroup()
# timer_cb_group = client_cb_group
self.cli = self.create_client(SumInt,sv,callback_group= self.group)
self.req = SumInt.Request()
self.call_timer = self.create_timer(1, self.get_result(), callback_group=self.group)
def send_req(self,a,b):
# b =5
# a = 8
start = time.time()
print("ok"+ str(time.time()))
self.req.a = a
self.req.b = b
self.future = self.cli.call_async(self.req)
self.executor.spin_once_until_future_complete(self, self.future)
print(self.future.result())
return self.future.result()
def main():
rclpy.init()
test_client =Test_client('Sum1')
test_client2 = Test_client('Sum2')
executor = MultiThreadedExecutor(3)
try:
executor.add_node(test_client)
executor.add_node(test_client2)
f1 = test_client.send_req(2,3)
f2 = test_client2.send_req(5,6)
try:
executor.spin()
finally:
test_client.destroy_node()
test_client2.destroy_node()
executor.shutdown()
finally:
rclpy.shutdown()
if __name__ == '__main__':
main()