Public Thread Local Storage API in Swift

Can the TLS API used by Observation be made public? It seems like it could be used in a lot of ways in multithreading.

1 Like

Foundation already has a general API for thread-local storage, though it requires going through objects:

I think a full Swift thread-local API would use generics to preserve types that go in and out of the dictionary (I can imagine one where the keys are themselves types which conform to a protocol), but for now this is both easier and safer than the thing in Observation.

If you're looking for an API right now™, you could technically just use the TaskLocal APIs because they set a thread local if there's no Task available: TaskLocal | Apple Developer Documentation

1 Like

That is what I am looking for, thanks!

1 Like

Oh? The documentation says it will use the default value:

A lookup made from the context of a synchronous function, that is not called from an asynchronous function (!), will immediately return the task-local’s default value.

Is that incorrect?


That's misleading wording... :frowning: Thanks for noticing, I'll send in a revamp of the docs.

Here's a test showcasing them working without any Task involved: swift/test/Concurrency/Runtime/async_task_locals_synchronous_bind.swift at main · apple/swift · GitHub


Gave the rewording a shot here: [docs] TaskLocal APIs from non-Task code by ktoso · Pull Request #70622 · apple/swift · GitHub