Post

Replies

Boosts

Views

Activity

Reply to Thread safety of os_activity_t
Thank you! You raise a good point with regard to scoping an activity across suspension points. os_activity_scope_{enter,leave} likely requires being called on the same thread even if the activity is automatically propagated across threads inside the scope. For non-detached Tasks this is simple as I can scope/apply the activity around the synchronous creation of the Task and the activity will be carried into the task automatically. Inside an async context I would probably need to ensure that I'm entering and leaving the scope on the same thread and even then it would likely break if that thread is used to run other work in the meantime. Hopefully we get Swift-native and Swift Concurrency compatible support for creating OS activities at some point, because they already work very well once created. They are even correctly propagated across custom non-GCD based TaskExecutors from what I can see. Restricting my use to non-detached Tasks is fine for now though, they are much more frequent than detached ones anyway. I guess the following would theoretically work to apply an activity inside an async-capable detached Task at the cost of an additional temporary Task: // create a temporary detached task to create a detached context to apply the activity in Task.detached(/* configure name, executor, priority as needed */) { // safely apply the activity os_activity_apply(activity) { // Spawn a non-detached task, inherit executor, priority and activity from the detached wrapper Task to run the actual operation // Use an immediate task to avoid a second scheduling delay Task.immediate(/* name appropriately */) { // run async work } } }
Topic: App & System Services SubTopic: Core OS Tags:
Oct ’25