Skip to content

Commit 0260884

Browse files
committed
reduce:overhead-queue
1 parent 0903691 commit 0260884

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

Sources/JavaScriptEventLoop/JobQueue.swift

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
// 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.
33

44
import _CJavaScriptEventLoop
5-
import Foundation
5+
import os.lock
66

77
/// Represents the state of the job queue.
88
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
@@ -15,16 +15,14 @@ struct QueueState: Sendable {
1515

1616
@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
1717
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()
2220

2321
/// Inserts a job into the queue and ensures jobs are processed.
2422
/// - Parameter job: The job to add to the queue.
2523
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) }
2826

2927
insertJob(newJob)
3028

@@ -79,8 +77,8 @@ extension JavaScriptEventLoop {
7977
/// Removes and returns the next job from the queue.
8078
/// - Returns: The next job in the queue, or `nil` if the queue is empty.
8179
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) }
8482

8583
guard let job = queueState.headJob else { return nil }
8684
queueState.headJob = job.nextInQueue().pointee
@@ -124,4 +122,4 @@ fileprivate struct JobFlags {
124122
var priority: UInt32 {
125123
(bits & 0xFF00) >> 8
126124
}
127-
}
125+
}

0 commit comments

Comments
 (0)