7.2. Threading model¶
Operations on the same Connector
instance or any contained Input
or Output
are, in general, not protected for multi-threaded access. The only
exceptions are the following wait operations.
- Thread-safe operations:
Connector.wait()
(wait for data on anyInput
)Output.wait()
(wait for acknowledgments)Output.wait_for_subscriptions()
Input.wait()
(wait for data on thisInput
)Input.wait_for_publications()
These operations can block a thread while the same Connector
is used in
a different thread.
Note
Currently Input.wait()
and Input.wait_for_publications()
cannot
both be called at the same time on the same Input
instance.
Note
Output.write()
can block the current thread under certain
circumstances, but Output.write()
is not thread-safe.
All operations on different Connector
instances are thread-safe.
Applications can implement their own thread-safety mechanism around a Connector
instance. The following section provides an example.
7.2.1. Protecting calls to Connector¶
This example shows how to use the Python threading
package to
protect calls to the same Connector
:
import threading
connector = rti.Connector("MyParticipantLibrary::MyParticipant", "ShapeExample.xml")
lock = threading.RLock()
def read_thread():
with lock: # Protect access to methods on the same Connector
input = connector.get_input("MySubscriber::MySquareReader")
input.wait() # wait outside the lock
with lock: # Take the lock again
input.take();
for sample in input.samples.valid_data_iter:
print(sample.get_dictionary())
def write_thread():
with lock: # Protect access to methods on the same Connector
output = connector.get_output("MyPublisher::MySquareWriter")
output.instance['x'] = 10
output.write()
# Spawn read_thread and write_thread...