DIT Robotics · Software courses · Example worksheetDIT Robotics · 軟體課程 · 範例學習單

Waiting inside a callback在 callback 裡等待

Every ROS 2 node is a program, and inside it one part decides which piece of your code runs next: the executor. In this session we freeze a node on purpose, find out exactly why it froze, and fix it in two ways. On the way you build a picture of the executor that explains a whole family of "my node just stopped" bugs.

每個 ROS 2 node 都是一個程式,程式裡有一個角色負責決定接下來跑你的哪一段程式碼:executor。這堂課我們故意讓一個 node 卡住,搞清楚它到底為什麼卡住,再用兩種方法修好。過程中你會建立對 executor 的理解,一整類「我的 node 突然不動了」的 bug 都能用它解釋。

How to use this page. The numbered Parts are what we do together in the session. Boxes and Parts marked Go deeper hold ideas that take longer to sink in. Skip them on the first pass. Come back to them after the session, or the day you meet the bug for real. The 中文 button (or the L key) switches the page to Chinese.

怎麼用這一頁。有編號的部分是課堂上一起做的。標成延伸的方塊和部分,放的是比較需要時間消化的觀念:第一次讀可以先跳過,課後再回來看,或等你真的遇到這個 bug 的那天。English 按鈕(或 L 鍵)可以切回英文。

Part 1第 1 部分A node that goes silent一個突然安靜的 node

Here is a small node, blocking_client. It has two timers. Every 0.5 s it prints heartbeat, so we can see it is alive. Every 3 s it asks a service, slow_server, to add 1 + 2. The server takes 2 s to answer.

這是一個小 node:blocking_client。它有兩個 timer。每 0.5 秒印一次 heartbeat,讓我們知道它還活著。每 3 秒請一個 service slow_server 算 1 + 2。server 要 2 秒才會回覆。

        self.create_timer(3.0, self.ask)
        self.create_timer(0.5, self.heartbeat)

    def ask(self):
        if not self.client.service_is_ready():
            return
        self.get_logger().info('calling...')
        result = self.client.call(AddTwoInts.Request(a=1, b=2))
        self.get_logger().info(f'result: {result.sum}')

    def heartbeat(self):
        self.get_logger().info('heartbeat')
...
rclpy.spin(BlockingClient())

Point at a highlighted line to see a note. The whole file is code/blocking_client.py.

把滑鼠移到標起來的那幾行,可以看到說明。完整檔案在 code/blocking_client.py。

I started the server in one terminal and the client in another, then merged their logs by time. Times are seconds since the client started, rounded to 0.1 s:

我在一個終端機開 server、另一個開 client,再把兩邊的 log 依時間合在一起。時間是 client 啟動後的秒數,取到 0.1 秒:

 0.5  [blocking_client] heartbeat
 1.0  [blocking_client] heartbeat
 1.5  [blocking_client] heartbeat
 2.0  [blocking_client] heartbeat
 2.5  [blocking_client] heartbeat
 3.0  [blocking_client] calling...
 3.0  [slow_server] got 1 + 2, working...
 5.0  [slow_server] replied 3
      (nothing more from blocking_client, ever)(之後 blocking_client 再也沒有輸出)

The server did its job: it replied at 5.0 s. Yet the client never printed the result. It also stopped printing heartbeat, although the heartbeat has nothing to do with the service. The process did not crash. It is still running, and doing nothing.

server 有做事:它在 5.0 秒回覆了。但 client 一直沒印出結果。它連 heartbeat 都不印了,雖然 heartbeat 跟 service 完全無關。程式沒有當掉,它還在跑,只是什麼都不做。

Why would a timer that only prints one word stop working because of a service call? Write your guess down. We come back to it at the end of Part 3.

只印一個字的 timer,為什麼會因為一次 service 呼叫就停掉?把你的猜測寫下來,第 3 部分結尾會回來看。

Part 2第 2 部分One thread, many callbacks一條執行緒,很多 callback

A callback is a function you give to ROS for ROS to call later, when something happens: a timer comes due, a message arrives, a reply arrives. ask and heartbeat are callbacks. You never call them yourself.

callback 是你交給 ROS、讓 ROS 在某件事發生時才呼叫的函式:timer 到期、message 到達、回覆到達。ask 和 heartbeat 都是 callback。你從來不會自己呼叫它們。

The part of ROS that calls them is the executor. rclpy.spin(node) creates one, a SingleThreadedExecutor, and runs it forever. A thread is one line of execution inside a program: it runs one instruction after another. This executor has exactly one, and that thread repeats three steps:

負責呼叫它們的是 executor。rclpy.spin(node) 會建立一個 SingleThreadedExecutor,然後永遠跑下去。執行緒(thread)是程式裡的一條執行路線:一個指令接著一個指令跑。這個 executor 只有一條,而這條執行緒一直重複三個步驟:

① Wait ① 等待 until at least one thing is ready 直到至少一件事準備好 timer heartbeat · every 0.5 s timer heartbeat · 每 0.5 秒 timer ask · every 3 s timer ask · 每 3 秒 reply from add_two_ints add_two_ints 的回覆 ② Take one ② 拿一個 a ready callback 準備好的 callback ③ Run it to the end ③ 跑到結束 on the one thread 在唯一的執行緒上 heartbeat() While it runs, nothing else in this node runs. 它在跑的時候,這個 node 的其他東西都不會跑。 then back to waiting, forever 然後回去等,永遠如此
The loop inside rclpy.spin(). Timers, messages and replies all wait in step ①, and they all need the same thread in step ③.rclpy.spin() 裡面的迴圈。timer、message、回覆都在步驟 ① 等待,也都需要步驟 ③ 的同一條執行緒。

A single-threaded executor runs one callback at a time, from start to finish. While a callback runs, the thread is busy, so every other timer, message and reply of this node waits. A callback that returns quickly costs nothing. A callback that takes a long time delays everything else.

single-threaded executor 一次只跑一個 callback,從頭跑到尾。callback 在跑的時候執行緒是忙的,這個 node 的其他 timer、message、回覆都得等。很快 return 的 callback 沒什麼成本;跑很久的 callback 會拖慢其他所有東西。

On a robot在機器人上
A slow callback makes a control loop late慢的 callback 讓控制迴圈遲到

Say one node runs a control loop on a 50 Hz timer, every 20 ms, and the same node also handles camera images in a callback that takes 100 ms. While an image is being handled, the control timer waits. The motors get no new command for 100 ms, five ticks in a row. Nothing crashes, and nothing in the log looks wrong: the robot just drives worse. The usual fix is to keep slow work out of the node that controls the motors.

假設一個 node 用 50 Hz 的 timer 跑控制迴圈(每 20 ms 一次),同一個 node 還有一個處理相機影像的 callback,每次要 100 ms。處理影像時,控制 timer 只能等。馬達有 100 ms 收不到新指令,連續漏掉五次。沒有東西當掉,log 裡也看不出異狀:機器人只是開得比較差。常見的解法是把慢的工作移出控制馬達的 node。

Part 3第 3 部分Waiting for a reply that cannot arrive等一個不可能到的回覆

Now look at call() again. It does two things: it sends the request, and then it makes the current thread wait until the reply has been handled. Who handles the reply? The reply is just one more thing that becomes ready in step ① of the loop. So the thread of the executor must take it and handle it, the same way it runs a timer.

再看一次 call()。它做兩件事:送出 request,然後讓目前這條執行緒等到回覆被處理完。誰來處理回覆?回覆只是迴圈步驟 ① 裡又一件準備好的事,所以必須由 executor 的執行緒拿去處理,就跟跑 timer 一樣。

The only thread that can handle the reply is the one waiting for it. Step through it before reading on.

唯一能處理回覆的執行緒,正是在等回覆的那一條。讀下去之前,先一步一步走一遍。

W1
Walkthrough 1: A wait that never ends. Follow the executor's one thread from spin() into call(), watch the reply arrive and wait, then replay the same moment with the first fix. 逐步解說 1:等不到的回覆。跟著 executor 唯一的執行緒,從 spin() 走進 call(),看回覆到了卻只能等,再用第一種修法重播同一個時刻。
Open walkthrough 1 ▶開啟逐步解說 1 ▶ 11 steps · ← → or a clicker · E for the explanation · L for 中文11 步 · ← → 或簡報筆 · E 看說明 · L 切換語言

The thread waits for the reply to be handled, and the reply waits for the thread to be free. Each waits for the other, so neither can move. This is a deadlock. Every other callback of the node waits behind the same thread, and that answers the question from Part 1: the heartbeat stopped because it needs the thread that is stuck in call().

執行緒在等回覆被處理,回覆在等執行緒有空。兩邊都在等對方,誰都動不了。這就是死結(deadlock)。這個 node 的其他 callback 也都排在同一條執行緒後面,這就回答了第 1 部分的問題:heartbeat 停了,是因為它需要的那條執行緒卡在 call() 裡。

Who誰is waiting for在等which needs而那需要
the thread, inside call()執行緒(在 call() 裡)the reply to be handled回覆被處理the thread執行緒
the reply回覆the thread to be free執行緒有空call() to returncall() return
the heartbeat timerheartbeat timerthe thread to be free執行緒有空call() to returncall() return

Part 4第 4 部分Two ways out兩種解法

There are two ways out. Either nobody waits inside a callback, or the reply gets a thread of its own.

有兩條路:要嘛沒有人在 callback 裡等,要嘛讓回覆有自己的執行緒。

Fix 1: don't wait修法 1:不要等

call_async() sends the request and returns at once. What it returns is a future: an object that will hold the reply later. We tell the future which function to run when the reply is in. That function is another callback, so the executor runs it like any other.

call_async() 送出 request 後馬上 return,回傳的是一個 future:之後會裝著回覆的物件。我們告訴 future,回覆到了要跑哪個函式。那個函式也是一個 callback,executor 會像跑其他 callback 一樣跑它。

    def ask(self):
        ...
        self.get_logger().info('calling...')
        future = self.client.call_async(AddTwoInts.Request(a=1, b=2))
        future.add_done_callback(self.on_reply)

    def on_reply(self, future):
        self.get_logger().info(f'result: {future.result().sum}')
 3.0  [async_client] calling...
 3.0  [async_client] heartbeat
 3.0  [slow_server] got 1 + 2, working...
 3.5  [async_client] heartbeat
 4.0  [async_client] heartbeat
 4.5  [async_client] heartbeat
 5.0  [async_client] heartbeat
 5.0  [slow_server] replied 3
 5.0  [async_client] result: 3

The heartbeat goes on while the server works, and the result arrives at 5.0 s. The cost is that the code after the call moves into a different function.

server 處理期間 heartbeat 照常,結果在 5.0 秒到達。代價是:呼叫之後的程式碼要搬到另一個函式裡。

Fix 2: give the executor more threads修法 2:給 executor 更多執行緒

A MultiThreadedExecutor has several threads, so it can run several callbacks at the same time. But more threads alone are not enough. By default, all callbacks of a node are in one callback group, and the executor never runs two callbacks of one such group at the same time. So we put the timer, the reply and the heartbeat into three separate groups:

MultiThreadedExecutor 有好幾條執行緒,可以同時跑好幾個 callback。但光有更多執行緒還不夠。預設情況下,一個 node 的所有 callback 都在同一個 callback group 裡,而 executor 不會同時跑同一個這種 group 裡的兩個 callback。所以我們把 timer、回覆和 heartbeat 分到三個不同的 group:

        self.client = self.create_client(AddTwoInts, 'add_two_ints',
                                         callback_group=MutuallyExclusiveCallbackGroup())
        self.create_timer(3.0, self.ask, callback_group=MutuallyExclusiveCallbackGroup())
        self.create_timer(0.5, self.heartbeat, callback_group=MutuallyExclusiveCallbackGroup())
...
        while rclpy.ok() and not future.done():
            time.sleep(0.1)
...
    executor = MultiThreadedExecutor()
    executor.add_node(GroupsClient())
    executor.spin()

The output looks like Fix 1's: heartbeats every 0.5 s during the wait, then result: 3 at 5.0 s. Waiting inside a callback is safe only if some other thread is free to deliver what you wait for.

輸出跟修法 1 差不多:等待期間每 0.5 秒一次 heartbeat,5.0 秒印出 result: 3。只有在別的執行緒有空、能把你在等的東西送來時,在 callback 裡等待才安全。

Fix 1: call_async + done callback修法 1:call_async + done callbackFix 2: more threads + callback groups修法 2:更多執行緒 + callback group
Threads執行緒one一條several好幾條
Where the code after the call goes呼叫之後的程式碼放哪into another function, on_reply搬到另一個函式 on_replystays right after the call留在呼叫的下一行
New things that can go wrong新的出錯可能few不多two callbacks can now touch the same data at once兩個 callback 可能同時改同一份資料
Use it when什麼時候用you can: it is the simpler choice能用就用:它比較簡單the code after the call must stay in order, step by step呼叫之後的程式碼必須照順序一步一步跑
Go deeper: why doesn't ROS give every callback its own thread?延伸:ROS 為什麼不讓每個 callback 都有自己的執行緒? read after the session課後再讀

It could, and you can ask for it: a ReentrantCallbackGroup lets its callbacks run on any number of threads at once. The price is that two callbacks may then change the same variable at the same moment. Suppose a pose callback writes self.x and then self.y, while a control callback on another thread reads both. The control callback can read the new x with the old y: a pose the robot was never at. This is a race condition. It shows up rarely and differently each time, which makes it one of the hardest bugs to find.

可以,而且你可以要求:ReentrantCallbackGroup 讓它的 callback 同時在任意多條執行緒上跑。代價是兩個 callback 可能在同一刻改同一個變數。假設 pose 的 callback 先寫 self.x 再寫 self.y,同時另一條執行緒上的控制 callback 在讀這兩個值。控制 callback 可能讀到新的 x 配舊的 y:一個機器人從來沒到過的位置。這叫 race condition。它很少出現,每次的樣子還不一樣,是最難找的 bug 之一。

That is why the default is the careful one: one group per node, one callback at a time. Each extra group is a decision that "these callbacks never share data, or protect it with a lock". Locks, and why they bring their own deadlocks, are a topic of OS‑2.

所以預設值選了保守的那一種:每個 node 一個 group,一次一個 callback。每多一個 group,就是在宣告「這些 callback 從不共用資料,或有用 lock 保護」。lock 以及它為什麼會帶來新的死結,是 OS‑2 的主題。

Try it動手試
Freeze a node, then fix it讓 node 卡住,再修好它

Do the one-time setup on the course home page if you haven't yet. Then, from the top of the repository:

如果還沒做過,先照課程首頁做一次設定。然後在 repository 的最上層:

docker run -it --rm --name ws0 -v "$PWD/_template/code":/code dit-course bash
cd /code && python3 slow_server.py

In a second terminal, docker exec -it ws0 bash, then cd /code. Before each run, say what you expect to see at t = 4 s.

開第二個終端機,docker exec -it ws0 bash,再 cd /code。每次執行前,先說出你預期 t = 4 秒時會看到什麼。

  1. python3 blocking_client.py. Wait for calling..., count to five, then press Ctrl+C. Keep the traceback: Part 5 reads it.python3 blocking_client.py。等它印出 calling...,數到五,按 Ctrl+C。把 traceback 留著:第 5 部分會讀它。
  2. python3 async_client.py. Do heartbeats appear between calling... and result: 3?python3 async_client.py。calling... 和 result: 3 之間有 heartbeat 嗎?
  3. python3 groups_client.py. Same question. Then put all three callbacks back into one group and run it again. What do you expect?python3 groups_client.py。同樣的問題。然後把三個 callback 放回同一個 group 再跑一次。你預期會怎樣?

Part 5 · Go deeper第 5 部分 · 延伸Inside call() and spin()call() 和 spin() 的內部

Everything in Parts 2 and 3 can be checked in rclpy's own source, which is plain Python. These excerpts are from ROS 2 Humble, with their real line numbers. rclpy.spin() is a loop around spin_once():

第 2、3 部分講的每件事,都可以在 rclpy 自己的原始碼裡驗證,它就是普通的 Python。以下節錄自 ROS 2 Humble,行號是真的。rclpy.spin() 是包著 spin_once() 的迴圈:

# rclpy/__init__.py
228      while executor.context.ok():
229          executor.spin_once()

and spin_once() of the single-threaded executor is steps ①, ② and ③ of the figure in Part 2:

而 single-threaded executor 的 spin_once(),就是第 2 部分圖裡的步驟 ①、②、③:

# rclpy/executors.py, SingleThreadedExecutor
797              handler, entity, node = self.wait_for_ready_callbacks(timeout_sec=timeout_sec)
798          except ShutdownException:
...
803              handler()

And here is call(). call() is just call_async() plus a wait.

再來是 call()。call() 就是 call_async() 加上一個等待。

# rclpy/client.py
84          event = threading.Event()
85
86          def unblock(future):
87              nonlocal event
88              event.set()
89
90          future = self.call_async(request)
91          future.add_done_callback(unblock)
...
96          if not future.done():
97              event.wait()

Put the pieces together. unblock() is a done callback, so the executor's thread must run it. That thread is asleep on line 97, waiting for unblock(). Now read the traceback you kept from the Try-it box. It lists the calls from the outside in, and the last lines show where the thread was when you pressed Ctrl+C:

把這些拼起來。unblock() 是 done callback,所以必須由 executor 的執行緒來跑。而那條執行緒正睡在第 97 行,等 unblock()。現在讀你在「動手試」留下的 traceback。它由外往內列出呼叫,最後幾行就是你按 Ctrl+C 時執行緒停在哪裡:

  File "/code/blocking_client.py", line 27, in main
    rclpy.spin(BlockingClient())
  File ".../rclpy/__init__.py", line 229, in spin
    executor.spin_once()
  File ".../rclpy/executors.py", line 803, in _spin_once_impl
    handler()
  ...
  File "/code/blocking_client.py", line 18, in ask
    result = self.client.call(AddTwoInts.Request(a=1, b=2))
  File ".../rclpy/client.py", line 97, in call
    event.wait()
  ...
KeyboardInterrupt

Read it from the top: spin ran handler() (step ③), the handler was our timer callback ask, ask called call(), and call() sat on line 97. A traceback of a frozen program tells you exactly where it is stuck. This works for any hanging Python node, not only this bug. py-spy dump --pid <PID> prints the same picture without stopping the program.

從上往下讀:spin 跑了 handler()(步驟 ③),handler 是我們的 timer callback ask,ask 呼叫了 call(),call() 停在第 97 行。卡住的程式,它的 traceback 會告訴你它卡在哪一行。這招適用於任何卡住的 Python node,不只這個 bug。py-spy dump --pid <PID> 可以在不停止程式的情況下印出同樣的資訊。

Real world真實案例
The warning was in the docs all along警告一直都寫在文件裡

The first lines of call()'s own documentation say: "Do not call this method in a callback or a deadlock may occur." The C++ API has the same trap: future.wait() or spin_until_future_complete() inside a callback freezes the node in the same way. In our test, Ctrl+C could not stop the C++ version; it needed Ctrl+\ (SIGQUIT).

call() 自己的文件開頭就寫著:"Do not call this method in a callback or a deadlock may occur."(不要在 callback 裡呼叫這個方法,否則可能死結。)C++ API 也有一樣的陷阱:在 callback 裡 future.wait() 或 spin_until_future_complete() 會用同樣的方式卡住 node。我們測試時,C++ 版本按 Ctrl+C 停不下來,要按 Ctrl+\(SIGQUIT)。

Sources: rclpy/client.py in ROS 2 Humble, Client.call; the C++ test is in ros2-basics/verify/README.md in this repository.

來源:ROS 2 Humble 的 rclpy/client.py,Client.call;C++ 的測試在本 repo 的 ros2-basics/verify/README.md。

Take home帶回家What you can now explain你現在能解釋的事

Tick each one you could explain to a teammate without looking at this page.

不看這一頁也能跟隊友解釋清楚的,就打勾。

Attribution出處Credits致謝