Skip to content

Commit 7790846

Browse files
Add WebWorkerDedicatedExecutor to run actors on a dedicated web worker thread
1 parent dd01077 commit 7790846

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import JavaScriptKit
2+
import _CJavaScriptEventLoop
3+
4+
#if canImport(Synchronization)
5+
import Synchronization
6+
#endif
7+
#if canImport(wasi_pthread)
8+
import wasi_pthread
9+
import WASILibc
10+
#endif
11+
12+
/// A serial executor that runs on a dedicated web worker thread.
13+
///
14+
/// This executor is useful for running actors on a dedicated web worker thread.
15+
///
16+
/// ## Usage
17+
///
18+
/// ```swift
19+
/// actor MyActor {
20+
/// let executor: WebWorkerDedicatedExecutor
21+
/// nonisolated var unownedExecutor: UnownedSerialExecutor {
22+
/// self.executor.asUnownedSerialExecutor()
23+
/// }
24+
/// init(executor: WebWorkerDedicatedExecutor) {
25+
/// self.executor = executor
26+
/// }
27+
/// }
28+
///
29+
/// let executor = try await WebWorkerDedicatedExecutor()
30+
/// let actor = MyActor(executor: executor)
31+
/// ```
32+
///
33+
/// - SeeAlso: ``WebWorkerTaskExecutor``
34+
@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
35+
public final class WebWorkerDedicatedExecutor: SerialExecutor {
36+
37+
private let underlying: WebWorkerTaskExecutor
38+
39+
/// - Parameters:
40+
/// - timeout: The maximum time to wait for all worker threads to be started. Default is 3 seconds.
41+
/// - checkInterval: The interval to check if all worker threads are started. Default is 5 microseconds.
42+
/// - Throws: An error if any worker thread fails to initialize within the timeout period.
43+
public init(timeout: Duration = .seconds(3), checkInterval: Duration = .microseconds(5)) async throws {
44+
let underlying = try await WebWorkerTaskExecutor(
45+
numberOfThreads: 1, timeout: timeout, checkInterval: checkInterval
46+
)
47+
self.underlying = underlying
48+
}
49+
50+
/// Terminates the worker thread.
51+
public func terminate() {
52+
self.underlying.terminate()
53+
}
54+
55+
// MARK: - SerialExecutor conformance
56+
57+
public func enqueue(_ job: consuming ExecutorJob) {
58+
self.underlying.enqueue(job)
59+
}
60+
}

0 commit comments

Comments
 (0)