1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
@_implementationOnly import CoreFoundation
#if canImport(Glibc)
import Glibc
#endif
#if os(Windows)
import WinSDK
#endif
public protocol NSLocking {
func lock()
func unlock()
}
extension NSLocking {
@_alwaysEmitIntoClient
@_disfavoredOverload
public func withLock<R>(_ body: () throws -> R) rethrows -> R {
self.lock()
defer {
self.unlock()
}
return try body()
}
}
#if os(Windows)
private typealias _MutexPointer = UnsafeMutablePointer<SRWLOCK>
private typealias _RecursiveMutexPointer = UnsafeMutablePointer<CRITICAL_SECTION>
private typealias _ConditionVariablePointer = UnsafeMutablePointer<CONDITION_VARIABLE>
#elseif CYGWIN || os(OpenBSD)
private typealias _MutexPointer = UnsafeMutablePointer<pthread_mutex_t?>
private typealias _RecursiveMutexPointer = UnsafeMutablePointer<pthread_mutex_t?>
private typealias _ConditionVariablePointer = UnsafeMutablePointer<pthread_cond_t?>
#else
private typealias _MutexPointer = UnsafeMutablePointer<pthread_mutex_t>
private typealias _RecursiveMutexPointer = UnsafeMutablePointer<pthread_mutex_t>
private typealias _ConditionVariablePointer = UnsafeMutablePointer<pthread_cond_t>
#endif
open class NSLock: NSObject, NSLocking, @unchecked Sendable {
internal var mutex = _MutexPointer.allocate(capacity: 1)
#if os(macOS) || os(iOS) || os(Windows)
private var timeoutCond = _ConditionVariablePointer.allocate(capacity: 1)
private var timeoutMutex = _MutexPointer.allocate(capacity: 1)
#endif
public override init() {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
InitializeSRWLock(mutex)
InitializeConditionVariable(timeoutCond)
InitializeSRWLock(timeoutMutex)
#else
pthread_mutex_init(mutex, nil)
#if os(macOS) || os(iOS)
pthread_cond_init(timeoutCond, nil)
pthread_mutex_init(timeoutMutex, nil)
#endif
#endif
}
deinit {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
// SRWLocks do not need to be explicitly destroyed
#else
pthread_mutex_destroy(mutex)
#endif
mutex.deinitialize(count: 1)
mutex.deallocate()
#if os(macOS) || os(iOS) || os(Windows)
deallocateTimedLockData(cond: timeoutCond, mutex: timeoutMutex)
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func lock() {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
AcquireSRWLockExclusive(mutex)
#else
pthread_mutex_lock(mutex)
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func unlock() {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
ReleaseSRWLockExclusive(mutex)
AcquireSRWLockExclusive(timeoutMutex)
WakeAllConditionVariable(timeoutCond)
ReleaseSRWLockExclusive(timeoutMutex)
#else
pthread_mutex_unlock(mutex)
#if os(macOS) || os(iOS)
// Wakeup any threads waiting in lock(before:)
pthread_mutex_lock(timeoutMutex)
pthread_cond_broadcast(timeoutCond)
pthread_mutex_unlock(timeoutMutex)
#endif
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func `try`() -> Bool {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
return true
#elseif os(Windows)
return TryAcquireSRWLockExclusive(mutex) != 0
#else
return pthread_mutex_trylock(mutex) == 0
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func lock(before limit: Date) -> Bool {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
if TryAcquireSRWLockExclusive(mutex) != 0 {
return true
}
#else
if pthread_mutex_trylock(mutex) == 0 {
return true
}
#endif
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
return true
#elseif os(macOS) || os(iOS) || os(Windows)
return timedLock(mutex: mutex, endTime: limit, using: timeoutCond, with: timeoutMutex)
#else
guard var endTime = timeSpecFrom(date: limit) else {
return false
}
return pthread_mutex_timedlock(mutex, &endTime) == 0
#endif
}
open var name: String?
}
extension NSLock {
internal func synchronized<T>(_ closure: () -> T) -> T {
self.lock()
defer { self.unlock() }
return closure()
}
}
#if SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
open class NSConditionLock : NSObject, NSLocking, @unchecked Sendable {
internal var _cond = NSCondition()
internal var _value: Int
internal var _thread: _swift_CFThreadRef?
public convenience override init() {
self.init(condition: 0)
}
public init(condition: Int) {
_value = condition
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func lock() {
let _ = lock(before: Date.distantFuture)
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func unlock() {
_cond.lock()
#if os(Windows)
_thread = INVALID_HANDLE_VALUE
#else
_thread = nil
#endif
_cond.broadcast()
_cond.unlock()
}
open var condition: Int {
return _value
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func lock(whenCondition condition: Int) {
let _ = lock(whenCondition: condition, before: Date.distantFuture)
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func `try`() -> Bool {
return lock(before: Date.distantPast)
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func tryLock(whenCondition condition: Int) -> Bool {
return lock(whenCondition: condition, before: Date.distantPast)
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func unlock(withCondition condition: Int) {
_cond.lock()
#if os(Windows)
_thread = INVALID_HANDLE_VALUE
#else
_thread = nil
#endif
_value = condition
_cond.broadcast()
_cond.unlock()
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func lock(before limit: Date) -> Bool {
_cond.lock()
while _thread != nil {
if !_cond.wait(until: limit) {
_cond.unlock()
return false
}
}
#if os(Windows)
_thread = GetCurrentThread()
#else
_thread = pthread_self()
#endif
_cond.unlock()
return true
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func lock(whenCondition condition: Int, before limit: Date) -> Bool {
_cond.lock()
while _thread != nil || _value != condition {
if !_cond.wait(until: limit) {
_cond.unlock()
return false
}
}
#if os(Windows)
_thread = GetCurrentThread()
#else
_thread = pthread_self()
#endif
_cond.unlock()
return true
}
open var name: String?
}
#endif
open class NSRecursiveLock: NSObject, NSLocking, @unchecked Sendable {
internal var mutex = _RecursiveMutexPointer.allocate(capacity: 1)
#if os(macOS) || os(iOS) || os(Windows)
private var timeoutCond = _ConditionVariablePointer.allocate(capacity: 1)
private var timeoutMutex = _MutexPointer.allocate(capacity: 1)
#endif
public override init() {
super.init()
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
InitializeCriticalSection(mutex)
InitializeConditionVariable(timeoutCond)
InitializeSRWLock(timeoutMutex)
#else
#if CYGWIN || os(OpenBSD)
var attrib : pthread_mutexattr_t? = nil
#else
var attrib = pthread_mutexattr_t()
#endif
withUnsafeMutablePointer(to: &attrib) { attrs in
pthread_mutexattr_init(attrs)
#if os(OpenBSD)
let type = Int32(PTHREAD_MUTEX_RECURSIVE.rawValue)
#else
let type = Int32(PTHREAD_MUTEX_RECURSIVE)
#endif
pthread_mutexattr_settype(attrs, type)
pthread_mutex_init(mutex, attrs)
}
#if os(macOS) || os(iOS)
pthread_cond_init(timeoutCond, nil)
pthread_mutex_init(timeoutMutex, nil)
#endif
#endif
}
deinit {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
DeleteCriticalSection(mutex)
#else
pthread_mutex_destroy(mutex)
#endif
mutex.deinitialize(count: 1)
mutex.deallocate()
#if os(macOS) || os(iOS) || os(Windows)
deallocateTimedLockData(cond: timeoutCond, mutex: timeoutMutex)
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func lock() {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
EnterCriticalSection(mutex)
#else
pthread_mutex_lock(mutex)
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func unlock() {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
LeaveCriticalSection(mutex)
AcquireSRWLockExclusive(timeoutMutex)
WakeAllConditionVariable(timeoutCond)
ReleaseSRWLockExclusive(timeoutMutex)
#else
pthread_mutex_unlock(mutex)
#if os(macOS) || os(iOS)
// Wakeup any threads waiting in lock(before:)
pthread_mutex_lock(timeoutMutex)
pthread_cond_broadcast(timeoutCond)
pthread_mutex_unlock(timeoutMutex)
#endif
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func `try`() -> Bool {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
return true
#elseif os(Windows)
return TryEnterCriticalSection(mutex)
#else
return pthread_mutex_trylock(mutex) == 0
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func lock(before limit: Date) -> Bool {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
if TryEnterCriticalSection(mutex) {
return true
}
#else
if pthread_mutex_trylock(mutex) == 0 {
return true
}
#endif
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
return true
#elseif os(macOS) || os(iOS) || os(Windows)
return timedLock(mutex: mutex, endTime: limit, using: timeoutCond, with: timeoutMutex)
#else
guard var endTime = timeSpecFrom(date: limit) else {
return false
}
return pthread_mutex_timedlock(mutex, &endTime) == 0
#endif
}
open var name: String?
}
open class NSCondition: NSObject, NSLocking, @unchecked Sendable {
internal var mutex = _MutexPointer.allocate(capacity: 1)
internal var cond = _ConditionVariablePointer.allocate(capacity: 1)
public override init() {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
InitializeSRWLock(mutex)
InitializeConditionVariable(cond)
#else
pthread_mutex_init(mutex, nil)
pthread_cond_init(cond, nil)
#endif
}
deinit {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
// SRWLock do not need to be explicitly destroyed
#else
pthread_mutex_destroy(mutex)
pthread_cond_destroy(cond)
#endif
mutex.deinitialize(count: 1)
cond.deinitialize(count: 1)
mutex.deallocate()
cond.deallocate()
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func lock() {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
AcquireSRWLockExclusive(mutex)
#else
pthread_mutex_lock(mutex)
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func unlock() {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
ReleaseSRWLockExclusive(mutex)
#else
pthread_mutex_unlock(mutex)
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func wait() {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
SleepConditionVariableSRW(cond, mutex, WinSDK.INFINITE, 0)
#else
pthread_cond_wait(cond, mutex)
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func wait(until limit: Date) -> Bool {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
return true
#elseif os(Windows)
return SleepConditionVariableSRW(cond, mutex, timeoutFrom(date: limit), 0)
#else
guard var timeout = timeSpecFrom(date: limit) else {
return false
}
return pthread_cond_timedwait(cond, mutex, &timeout) == 0
#endif
}
@available(*, noasync, message: "Use async-safe scoped locking instead")
open func signal() {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
WakeConditionVariable(cond)
#else
pthread_cond_signal(cond)
#endif
}
open func broadcast() {
#if !SWIFT_CORELIBS_FOUNDATION_HAS_THREADS
// noop on no thread platforms
#elseif os(Windows)
WakeAllConditionVariable(cond)
#else
pthread_cond_broadcast(cond)
#endif
}
open var name: String?
}
#if os(Windows)
private func timeoutFrom(date: Date) -> DWORD {
guard date.timeIntervalSinceNow > 0 else { return 0 }
return DWORD(date.timeIntervalSinceNow * 1000)
}
#else
private func timeSpecFrom(date: Date) -> timespec? {
guard date.timeIntervalSinceNow > 0 else {
return nil
}
let nsecPerSec: Int64 = 1_000_000_000
let interval = date.timeIntervalSince1970
let intervalNS = Int64(interval * Double(nsecPerSec))
return timespec(tv_sec: time_t(intervalNS / nsecPerSec),
tv_nsec: Int(intervalNS % nsecPerSec))
}
#endif
#if os(macOS) || os(iOS) || os(Windows)
private func deallocateTimedLockData(cond: _ConditionVariablePointer, mutex: _MutexPointer) {
#if os(Windows)
// CONDITION_VARIABLEs do not need to be explicitly destroyed
#else
pthread_cond_destroy(cond)
#endif
cond.deinitialize(count: 1)
cond.deallocate()
#if os(Windows)
// SRWLOCKs do not need to be explicitly destroyed
#else
pthread_mutex_destroy(mutex)
#endif
mutex.deinitialize(count: 1)
mutex.deallocate()
}
// Emulate pthread_mutex_timedlock using pthread_cond_timedwait.
// lock(before:) passes a condition variable/mutex pair to use.
// unlock() will use pthread_cond_broadcast() to wake any waits in progress.
#if os(Windows)
private func timedLock(mutex: _MutexPointer, endTime: Date,
using timeoutCond: _ConditionVariablePointer,
with timeoutMutex: _MutexPointer) -> Bool {
repeat {
AcquireSRWLockExclusive(timeoutMutex)
SleepConditionVariableSRW(timeoutCond, timeoutMutex,
timeoutFrom(date: endTime), 0)
ReleaseSRWLockExclusive(timeoutMutex)
if TryAcquireSRWLockExclusive(mutex) != 0 {
return true
}
} while timeoutFrom(date: endTime) != 0
return false
}
private func timedLock(mutex: _RecursiveMutexPointer, endTime: Date,
using timeoutCond: _ConditionVariablePointer,
with timeoutMutex: _MutexPointer) -> Bool {
repeat {
AcquireSRWLockExclusive(timeoutMutex)
SleepConditionVariableSRW(timeoutCond, timeoutMutex,
timeoutFrom(date: endTime), 0)
ReleaseSRWLockExclusive(timeoutMutex)
if TryEnterCriticalSection(mutex) {
return true
}
} while timeoutFrom(date: endTime) != 0
return false
}
#else
private func timedLock(mutex: _MutexPointer, endTime: Date,
using timeoutCond: _ConditionVariablePointer,
with timeoutMutex: _MutexPointer) -> Bool {
var timeSpec = timeSpecFrom(date: endTime)
while var ts = timeSpec {
let lockval = pthread_mutex_lock(timeoutMutex)
precondition(lockval == 0)
let waitval = pthread_cond_timedwait(timeoutCond, timeoutMutex, &ts)
precondition(waitval == 0 || waitval == ETIMEDOUT)
let unlockval = pthread_mutex_unlock(timeoutMutex)
precondition(unlockval == 0)
if waitval == ETIMEDOUT {
return false
}
let tryval = pthread_mutex_trylock(mutex)
precondition(tryval == 0 || tryval == EBUSY)
if tryval == 0 { // The lock was obtained.
return true
}
// pthread_cond_timedwait didn't timeout so wait some more.
timeSpec = timeSpecFrom(date: endTime)
}
return false
}
#endif
#endif
|