Skip to content

Commit 8b069b9

Browse files
committed
Use of THREAD_TIME_CONSTRAINT_POLICY in setSoftRealTimePriority()
Signed-off-by: Dhruv Patel <[email protected]>
1 parent d2b4ddb commit 8b069b9

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

nav2_ros_common/include/nav2_ros_common/node_utils.hpp

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -349,25 +349,28 @@ inline std::string get_plugin_type_param(
349349
inline void setSoftRealTimePriority()
350350
{
351351
#ifdef __APPLE__
352-
// macOS: Use Mach thread API (approximate real-time priority)
352+
// macOS: Use Mach thread API to approximate real-time scheduling
353353
thread_port_t thread = pthread_mach_thread_np(pthread_self());
354-
thread_precedence_policy_data_t policy;
355-
policy.importance = 63; // 0–63, higher = more priority
354+
355+
thread_time_constraint_policy_data_t policy;
356+
policy.period = 1000; // in microseconds (1 kHz loop)
357+
policy.computation = 800; // expected compute time per period
358+
policy.constraint = 1000; // max latency
359+
policy.preemptible = 1; // allow preemption by higher-priority threads
360+
356361
kern_return_t result = thread_policy_set(
357362
thread,
358-
THREAD_PRECEDENCE_POLICY,
363+
THREAD_TIME_CONSTRAINT_POLICY,
359364
(thread_policy_t)&policy,
360-
THREAD_PRECEDENCE_POLICY_COUNT);
365+
THREAD_TIME_CONSTRAINT_POLICY_COUNT
366+
);
361367

362368
if (result != KERN_SUCCESS) {
363-
// Construct the message once with the full context
364369
std::string errmsg =
365-
"Failed to set THREAD_PRECEDENCE_POLICY on macOS. "
366-
"Thread priority remains at default. "
367-
"Mach Error Code: ";
368-
369-
// Append the numerical result code and throw
370-
throw std::runtime_error(errmsg + std::to_string(result));
370+
"Failed to set THREAD_TIME_CONSTRAINT_POLICY on macOS. "
371+
"Thread remains at default priority. Mach Error Code: " +
372+
std::to_string(result);
373+
throw std::runtime_error(errmsg);
371374
}
372375
#else
373376
// Linux: True real-time scheduling (requires privileges)

0 commit comments

Comments
 (0)