Skip to content

Commit 8981c51

Browse files
authored
Utility: add a Windows path to the synchronisation support (#603)
Use a `SRWLOCK` on Windows to support locking. Slim Reader-Writer locks are lightweight mutexes that closely resemble `pthread_mutex_t` in functionality. While possible to use `WaitOnAddress` to implement `os_unfair_lock`, that would be more complex and a slightly heavier mutex as a starting point seems reasonable. If it turns out that the performance really requires an even lighter weight locking primitive, we can refine this to `WaitOnAddress` subsequently.
1 parent 75477a6 commit 8981c51

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

Sources/SwiftDocC/Utility/Synchronization.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
*/
1010

1111
import Foundation
12+
#if os(Windows)
13+
import WinSDK
14+
#endif
1215

1316
/// A wrapper type that ensures a synchronous access to a value.
1417
///
@@ -32,6 +35,8 @@ public class Synchronized<Value> {
3235
#elseif os(Linux) || os(Android)
3336
/// A lock type appropriate for the current platform.
3437
var lock: UnsafeMutablePointer<pthread_mutex_t>
38+
#elseif os(Windows)
39+
var lock: UnsafeMutablePointer<SRWLOCK>
3540
#else
3641
#error("Unsupported platform")
3742
#endif
@@ -48,6 +53,9 @@ public class Synchronized<Value> {
4853
lock = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
4954
lock.initialize(to: pthread_mutex_t())
5055
pthread_mutex_init(lock, nil)
56+
#elseif os(Windows)
57+
lock = UnsafeMutablePointer<SRWLOCK>.allocate(capacity: 1)
58+
InitializeSRWLock(lock)
5159
#else
5260
#error("Unsupported platform")
5361
#endif
@@ -69,6 +77,9 @@ public class Synchronized<Value> {
6977
#elseif os(Linux) || os(Android)
7078
pthread_mutex_lock(lock)
7179
defer { pthread_mutex_unlock(lock) }
80+
#elseif os(Windows)
81+
AcquireSRWLockExclusive(lock)
82+
defer { ReleaseSRWLockExclusive(lock) }
7283
#else
7384
#error("Unsupported platform")
7485
#endif
@@ -102,6 +113,9 @@ public extension Lock {
102113
#elseif os(Linux) || os(Android)
103114
pthread_mutex_lock(lock)
104115
defer { pthread_mutex_unlock(lock) }
116+
#elseif os(Windows)
117+
AcquireSRWLockExclusive(lock)
118+
defer { ReleaseSRWLockExclusive(lock) }
105119
#else
106120
#error("Unsupported platform")
107121
#endif

0 commit comments

Comments
 (0)