Skip to content

Port LockedState and _ThreadLocal to WASI without any locking #780

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Sources/FoundationEssentials/LockedState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ package struct LockedState<State> {
typealias Primitive = pthread_mutex_t
#elseif canImport(WinSDK)
typealias Primitive = SRWLOCK
#elseif os(WASI)
// WASI is single-threaded, so we don't need a lock.
typealias Primitive = Void
#endif

typealias PlatformLock = UnsafeMutablePointer<Primitive>
Expand All @@ -45,6 +48,8 @@ package struct LockedState<State> {
pthread_mutex_init(platformLock, nil)
#elseif canImport(WinSDK)
InitializeSRWLock(platformLock)
#elseif os(WASI)
// no-op
#endif
}

Expand All @@ -62,6 +67,8 @@ package struct LockedState<State> {
pthread_mutex_lock(platformLock)
#elseif canImport(WinSDK)
AcquireSRWLockExclusive(platformLock)
#elseif os(WASI)
// no-op
#endif
}

Expand All @@ -72,6 +79,8 @@ package struct LockedState<State> {
pthread_mutex_unlock(platformLock)
#elseif canImport(WinSDK)
ReleaseSRWLockExclusive(platformLock)
#elseif os(WASI)
// no-op
#endif
}
}
Expand Down
8 changes: 8 additions & 0 deletions Sources/FoundationEssentials/_ThreadLocal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ struct _ThreadLocal {
fileprivate typealias PlatformKey = tss_t
#elseif canImport(WinSDK)
fileprivate typealias PlatformKey = DWORD
#elseif os(WASI)
fileprivate typealias PlatformKey = UnsafeMutablePointer<UnsafeMutableRawPointer?>
#endif

struct Key<Value> {
Expand All @@ -46,6 +48,8 @@ struct _ThreadLocal {
self.key = key
#elseif canImport(WinSDK)
key = FlsAlloc(nil)
#elseif os(WASI)
key = UnsafeMutablePointer<UnsafeMutableRawPointer?>.allocate(capacity: 1)
#endif
}
}
Expand All @@ -58,6 +62,8 @@ struct _ThreadLocal {
tss_get(key)
#elseif canImport(WinSDK)
FlsGetValue(key)
#elseif os(WASI)
key.pointee
#endif
}

Expand All @@ -68,6 +74,8 @@ struct _ThreadLocal {
tss_set(key, newValue)
#elseif canImport(WinSDK)
FlsSetValue(key, newValue)
#elseif os(WASI)
key.pointee = newValue
#endif
}
}
Expand Down