<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Multi-threaded Publish and Subscribe - safe_drive: Formally Specified Rust Bindings for ROS2</title>
<!-- Custom HTML head -->
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="favicon.svg">
<link rel="shortcut icon" href="favicon.png">
<link rel="stylesheet" href="css/variables.css">
<link rel="stylesheet" href="css/general.css">
<link rel="stylesheet" href="css/chrome.css">
<link rel="stylesheet" href="css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<link rel="stylesheet" href="ayu-highlight.css">
<!-- Custom theme stylesheets -->
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded "><a href="index.html"><strong aria-hidden="true">1.</strong> Top</a></li><li class="chapter-item expanded "><a href="tutorial.html"><strong aria-hidden="true">2.</strong> Tutorial</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="setup.html"><strong aria-hidden="true">2.1.</strong> Setting-up</a></li><li class="chapter-item expanded "><a href="pubsub.html"><strong aria-hidden="true">2.2.</strong> Publish and Subscribe</a></li><li class="chapter-item expanded "><a href="timer.html"><strong aria-hidden="true">2.3.</strong> Timer</a></li><li class="chapter-item expanded "><a href="multi_pubsub.html" class="active"><strong aria-hidden="true">2.4.</strong> Multi-threaded Publish and Subscribe</a></li><li class="chapter-item expanded "><a href="message.html"><strong aria-hidden="true">2.5.</strong> User Defined Data Structure</a></li><li class="chapter-item expanded "><a href="service.html"><strong aria-hidden="true">2.6.</strong> Service</a></li><li class="chapter-item expanded "><a href="parameter.html"><strong aria-hidden="true">2.7.</strong> Parameter</a></li><li class="chapter-item expanded "><a href="zerocopy.html"><strong aria-hidden="true">2.8.</strong> Zero Copy Publish and Subscribe</a></li><li class="chapter-item expanded "><a href="allocator.html"><strong aria-hidden="true">2.9.</strong> Custom Memory Allocator</a></li><li class="chapter-item expanded "><a href="pusbsub_and_service.html"><strong aria-hidden="true">2.10.</strong> Request to Server in Callback</a></li></ol></li><li class="chapter-item expanded "><a href="contribution.html"><strong aria-hidden="true">3.</strong> Contribution Guide</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="setup_contribution.html"><strong aria-hidden="true">3.1.</strong> Setting-up for Contribution</a></li><li class="chapter-item expanded "><a href="build_and_test.html"><strong aria-hidden="true">3.2.</strong> Build and Test</a></li><li class="chapter-item expanded "><a href="editor_setup.html"><strong aria-hidden="true">3.3.</strong> Editor Setting-up</a></li><li class="chapter-item expanded "><a href="internal_msgs.html"><strong aria-hidden="true">3.4.</strong> Generating Messages Included by safe_drive</a></li><li class="chapter-item expanded "><a href="c_apis.html"><strong aria-hidden="true">3.5.</strong> C APIs</a></li><li class="chapter-item expanded "><a href="document.html"><strong aria-hidden="true">3.6.</strong> Documentation</a></li></ol></li></ol>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">safe_drive: Formally Specified Rust Bindings for ROS2</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="multi-threaded-publish-and-subscribe"><a class="header" href="#multi-threaded-publish-and-subscribe">Multi-threaded Publish and Subscribe</a></h1>
<p><a href="https://github.com/tier4/safe_drive_tutorial/tree/main/mt_pubsub">Source code</a>.</p>
<p>Previous chapters use a selector to wait messages.
A selector can be used by only a single thread.
This means previous implementation is single-threaded.</p>
<p>To execute tasks concurrently, we can use the async/await feature of Rust.
By using this, we can implement multi-threaded applications.
In this chapter, we will describe how to use <code>safe_drive</code> with async/await.
We use <code>async_std</code> as a asynchronous library,
but you can use <code>Tokio</code> instead.</p>
<h2 id="creating-projects"><a class="header" href="#creating-projects">Creating Projects</a></h2>
<p>Before implementing, we need to prepare projects as follows.</p>
<pre><code class="language-text">$ mkdir -p mt_pubsub/src
$ cd mt_pubsub/src
$ cargo new publishers
$ cargo new subscribers
</code></pre>
<p>The <code>mt_pubsub</code> is the root directory of this project,
and we created <code>publishers</code> and <code>subscribers</code> of Rust's projects.
At the moment, the following directories is present.</p>
<div class="table-wrapper"><table><thead><tr><th>Directories</th><th>What?</th></tr></thead><tbody>
<tr><td>mt_pubsub/src/publishers</td><td>publishers in Rust</td></tr>
<tr><td>mt_pubsub/src/subscribers</td><td>subscribers in Rust</td></tr>
</tbody></table>
</div>
<h2 id="common-configuration"><a class="header" href="#common-configuration">Common Configuration</a></h2>
<p>Then, we have to create or edit the following files for basic configurations.</p>
<div class="table-wrapper"><table><thead><tr><th>Files</th><th>What?</th></tr></thead><tbody>
<tr><td>mt_pubsub/src/publishers/Cargo.toml</td><td>for Cargo</td></tr>
<tr><td>mt_pubsub/src/publishers/package.xml</td><td>for ROS2</td></tr>
<tr><td>mt_pubsub/src/publishers/build.rs</td><td>for rustc</td></tr>
<tr><td>mt_pubsub/src/subscribers/Cargo.toml</td><td>for Cargo</td></tr>
<tr><td>mt_pubsub/src/subscribers/package.xml</td><td>for ROS2</td></tr>
<tr><td>mt_pubsub/src/subscribers/build.rs</td><td>for rustc</td></tr>
<tr><td>mt_pubsub/src/Cargo.toml</td><td>for Cargo's workspace</td></tr>
</tbody></table>
</div>
<p>To enable rust-analyzer in the <code>mt_pubsub</code> directory and reduce the compilation time,
prepare workspace's <code>Cargo.toml</code> as follows.</p>
<p><code>mt_pubsub/src/Cargo.toml</code></p>
<pre><code class="language-toml">[workspace]
members = ["publishers", "subscribers"]
</code></pre>
<p><code>package.xml</code>s are almost same as <a href="./pubsub.html">Publish and Subscribe</a>.
If you cannot understand what these files do,
please go back to the previous chapter.</p>
<p><code>publishers/package.xml</code></p>
<pre><code class="language-xml"><?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>publishers</name>
<version>0.0.0</version>
<description>MT-Publishers</description>
<maintainer email="yuuki.takano@tier4.jp">Yuuki Takano</maintainer>
<license>Apache License 2.0</license>
<depend>std_msgs</depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<export>
<build_type>ament_cargo</build_type>
</export>
</package>
</code></pre>
<p><code>subscribers/package.xml</code></p>
<pre><code class="language-xml"> <name>subscribers</name>
<description>MT-Subscribers</description>
</code></pre>
<p>To use <code>async_std</code>, we have to update <code>Cargo.toml</code> as follows.</p>
<p><code>Cargo.toml</code></p>
<pre><code class="language-toml">[dependencies]
async-std = { version = "1", features = ["attributes"] }
safe_drive = "0.4"
std_msgs = { path = "/tmp/safe_drive_tutorial/mt_pubsub/std_msgs" }
[package.metadata.ros]
msg = ["std_msgs"]
msg_dir = "/tmp/safe_drive_tutorial/mt_pubsub"
safe_drive_version = "0.3"
</code></pre>
<h2 id="publishers"><a class="header" href="#publishers">Publishers</a></h2>
<p>The <code>publishers</code> publishes messages to 2 topics periodically.
This create 2 tasks.
One is send a message every 500ms,
and another is send a message every 250ms.
The code of the <code>publishers</code> is as follows.</p>
<p><code>mt_pubsub/src/publishers/src/main.rs</code></p>
<pre><pre class="playground"><code class="language-rust">use safe_drive::{context::Context, error::DynError};
use std::time::Duration;
#[async_std::main]
async fn main() -> Result<(), DynError> {
// Create a context and a node.
let ctx = Context::new()?;
let node = ctx.create_node("publishers", None, Default::default())?;
// Create publishers.
let publisher1 = node.create_publisher::<std_msgs::msg::String>("topic1", None)?;
let publisher2 = node.create_publisher::<std_msgs::msg::String>("topic2", None)?;
// Create a task which sends "Hello, World!".
let task1 = async_std::task::spawn(async move {
let mut msg = std_msgs::msg::String::new().unwrap();
msg.data.assign("Hello, World!");
for _ in 0..50 {
publisher1.send(&msg).unwrap(); // Send a message.
async_std::task::sleep(Duration::from_millis(500)).await; // Sleep 500ms.
}
});
// Create a task which sends "Hello, Universe!".
let task2 = async_std::task::spawn(async move {
let mut msg = std_msgs::msg::String::new().unwrap();
msg.data.assign("Hello, Universe!");
for _ in 0..100 {
publisher2.send(&msg).unwrap(); // Send a message.
async_std::task::sleep(Duration::from_millis(250)).await; // Sleep 250ms.
}
});
task1.await;
task2.await;
Ok(())
}</code></pre></pre>
<p>The <code>async_std::task::spawn</code> creates a asynchronous task,
which is similar to a thread.
The following is a excerpt creating a task which sends "Hello, World!"
to "topic1" every 500ms.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// Create a task which sends "Hello, World!".
let task1 = async_std::task::spawn(async move {
let mut msg = std_msgs::msg::String::new().unwrap();
msg.data.assign("Hello, World!");
for _ in 0..50 {
publisher1.send(&msg).unwrap(); // Send a message.
async_std::task::sleep(Duration::from_millis(500)).await; // Sleep 500ms.
}
});
<span class="boring">}</span></code></pre></pre>
<p>This excerpt sends a message by <code>Publisher::send</code> and sleep by <code>async_std::task::sleep</code>.
Note that this uses <code>async_std::task::sleep</code> instead of <code>std::thread::sleep</code>,
because the former is non-blocking but the the latter is blocking.
Calling blocking functions should be avoided in asynchronous tasks.</p>
<h2 id="subscribers"><a class="header" href="#subscribers">Subscribers</a></h2>
<p>Then, let's implement the <code>subscribers</code>.
The main function is almost same as previous one.</p>
<p><code>mt_pubsub/src/subscribers/src/main</code></p>
<pre><pre class="playground"><code class="language-rust">use safe_drive::{
context::Context, error::DynError, logger::Logger, pr_info, topic::subscriber::Subscriber,
};
#[async_std::main]
async fn main() -> Result<(), DynError> {
// Create a context and a node.
let ctx = Context::new()?;
let node = ctx.create_node("subscribers", None, Default::default())?;
// Create subscribers.
let subscriber1 = node.create_subscriber::<std_msgs::msg::String>("topic1", None)?;
let subscriber2 = node.create_subscriber::<std_msgs::msg::String>("topic2", None)?;
// Receive messages.
let task1 = async_std::task::spawn(receiver(subscriber1));
let task2 = async_std::task::spawn(receiver(subscriber2));
task1.await?;
task2.await?;
Ok(())
}
async fn receiver(mut subscriber: Subscriber<std_msgs::msg::String>) -> Result<(), DynError> {
let logger = Logger::new(subscriber.get_topic_name());
loop {
// Receive a message
let msg = subscriber.recv().await?;
pr_info!(logger, "{}", msg.data);
}
}</code></pre></pre>
<p><code>Subscriber::recv</code> is an asynchronous function to receive a message.
To receive asynchronously, use the <code>.await</code> keyword.
If there is a message to be received, <code>recv().await</code> returns the message immediately.
Otherwise, it yields the execution to another task and sleeps until arriving a message.</p>
<h3 id="modification-for-timeout"><a class="header" href="#modification-for-timeout">Modification for Timeout</a></h3>
<p>By using a timeout mechanism provided by asynchronous libraries,
we can implement receiving with timeout.
Timeout can be implemented as follows.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use async_std::future::timeout;
use safe_drive::pr_warn;
use std::time::Duration;
async fn receiver(mut subscriber: Subscriber<std_msgs::msg::String>) -> Result<(), DynError> {
let logger = Logger::new(subscriber.get_topic_name());
loop {
// Receive a message with 3s timeout.
match timeout(Duration::from_secs(3), subscriber.recv()).await {
Ok(result) => pr_info!(logger, "received: {}", result?.data),
Err(_) => {
// Timed out. Finish receiving.
pr_warn!(logger, "timeout");
break;
}
}
}
Ok(())
}
<span class="boring">}</span></code></pre></pre>
<p><code>async_std::timeout</code> is a function to represent timeout.
<code>timeout(Duration::from_secs(3), subscriber.recv()).await</code> calls <code>subscriber.recv()</code> asynchronously,
but it will be timed out after 3s later.</p>
<h2 id="execution"><a class="header" href="#execution">Execution</a></h2>
<p>First, execute <code>publishers</code> in a terminal application window as follows.</p>
<pre><code class="language-text">$ cd mt_pubsub
$ colcon build --cargo-args --release
$ . ./install/setup.bash
$ ros2 run publishers publishers
</code></pre>
<p>Then, execute <code>subscribers</code> in another terminal application window as follows.
This uses timeout for receiving.</p>
<pre><code class="language-text">$ cd mt_pubsub.
$ . ./install/setup.bash
$ ros2 run subscribers subscribers
[INFO] [1657076046.969809600] [topic2]: received: Hello, Universe!
[INFO] [1657076047.220104100] [topic2]: received: Hello, Universe!
[INFO] [1657076047.447426100] [topic1]: received: Hello, World!
[INFO] [1657076047.470348600] [topic2]: received: Hello, Universe!
[INFO] [1657076047.721980900] [topic2]: received: Hello, Universe!
[WARN] [1657076050.448393200] [topic1]: timeout
[WARN] [1657076050.722433800] [topic2]: timeout
</code></pre>
<p>Nicely done!
We are sending and receiving messages asynchronously.
In addition to that, the timeouts work correctly.</p>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="timer.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="message.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="timer.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="message.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="elasticlunr.min.js"></script>
<script src="mark.min.js"></script>
<script src="searcher.js"></script>
<script src="clipboard.min.js"></script>
<script src="highlight.js"></script>
<script src="book.js"></script>
<!-- Custom JS scripts -->
<script src="mermaid.min.js"></script>
<script src="mermaid-init.js"></script>
</div>
</body>
</html>