1
1
// This file contains the job queue implementation for JavaScriptEventLoop.
2
- // It manages job insertion and execution based on priority.
2
+ // It manages job insertion and execution based on priority, ensuring thread safety and performance .
3
3
4
4
import _CJavaScriptEventLoop
5
- import Foundation
5
+ import os . lock
6
6
7
7
/// Represents the state of the job queue.
8
8
@available ( macOS 10 . 15 , iOS 13 . 0 , watchOS 6 . 0 , tvOS 13 . 0 , * )
@@ -15,16 +15,14 @@ struct QueueState: Sendable {
15
15
16
16
@available ( macOS 14 . 0 , iOS 17 . 0 , watchOS 10 . 0 , tvOS 17 . 0 , * )
17
17
extension JavaScriptEventLoop {
18
- /// A lock to synchronize queue access.
19
- private var queueLock : NSLock {
20
- NSLock ( )
21
- }
18
+ /// A lock to synchronize queue access using `os_unfair_lock` for lightweight thread safety.
19
+ private static var queueLock = os_unfair_lock_s ( )
22
20
23
21
/// Inserts a job into the queue and ensures jobs are processed.
24
22
/// - Parameter job: The job to add to the queue.
25
23
func insertJobQueue( job newJob: UnownedJob ) {
26
- queueLock . lock ( )
27
- defer { queueLock . unlock ( ) }
24
+ os_unfair_lock_lock ( & JavaScriptEventLoop . queueLock )
25
+ defer { os_unfair_lock_unlock ( & JavaScriptEventLoop . queueLock ) }
28
26
29
27
insertJob ( newJob)
30
28
@@ -79,8 +77,8 @@ extension JavaScriptEventLoop {
79
77
/// Removes and returns the next job from the queue.
80
78
/// - Returns: The next job in the queue, or `nil` if the queue is empty.
81
79
func claimNextFromQueue( ) -> UnownedJob ? {
82
- queueLock . lock ( )
83
- defer { queueLock . unlock ( ) }
80
+ os_unfair_lock_lock ( & JavaScriptEventLoop . queueLock )
81
+ defer { os_unfair_lock_unlock ( & JavaScriptEventLoop . queueLock ) }
84
82
85
83
guard let job = queueState. headJob else { return nil }
86
84
queueState. headJob = job. nextInQueue ( ) . pointee
@@ -124,4 +122,4 @@ fileprivate struct JobFlags {
124
122
var priority : UInt32 {
125
123
( bits & 0xFF00 ) >> 8
126
124
}
127
- }
125
+ }
0 commit comments