Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Give a forwarder test's loopback server its own thread and listener

Lakr2331130aa2d99aa
diff --git a/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneTCPForwarderTests.swift b/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneTCPForwarderTests.swift
index 124a979c..c87102b4 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneTCPForwarderTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneTCPForwarderTests.swift
@@ -160,12 +160,12 @@ struct VPhoneTCPForwarderTests {
/// has something real to terminate against.
private final class LoopbackServer: @unchecked Sendable {
let port: UInt16
- private let listener: Int32
private let received = Box(0)
private let finished = Box(false)
+ private let stopped = Box(false)
- /// - Parameter session: runs with the accepted socket on a background
- /// queue and owns closing it.
+ /// - Parameter session: runs with the accepted socket on the server's
+ /// own thread and owns closing it.
init(session: @escaping @Sendable (Int32, LoopbackServer) -> Void) throws {
let descriptor = socket(AF_INET, SOCK_STREAM, 0)
guard descriptor >= 0 else { throw Error.socketFailed }
@@ -194,16 +194,29 @@ struct VPhoneTCPForwarderTests {
}
}
port = UInt16(bigEndian: assigned.sin_port)
- listener = descriptor
let server = self
- DispatchQueue.global().async {
+ // A thread of its own, not a global queue: in a full CoreKit run a
+ // block queued there started 2 to 3.5 s late, all of it counted
+ // against the throughput test.
+ Thread {
+ // Only this thread closes the listener. Closed by stop() while
+ // the accept had yet to run, its number went to the next test's
+ // listener, and the late accept below took that test's
+ // connection: a forwarder handshake does not wait for accept.
+ defer { close(descriptor) }
+ var listening = pollfd(fd: descriptor, events: Int16(POLLIN), revents: 0)
+ while poll(&listening, 1, 50) <= 0 {
+ if server.stopped.withLock({ $0 }) {
+ return
+ }
+ }
let client = accept(descriptor, nil, nil)
defer { server.finished.withLock { $0 = true } }
guard client >= 0 else { return }
defer { close(client) }
session(client, server)
- }
+ }.start()
}
/// Bytes pulled out of the socket by the session.
@@ -240,8 +253,9 @@ struct VPhoneTCPForwarderTests {
}
}
+ /// Stop waiting for a connection; the server's thread closes the listener.
func stop() {
- close(listener)
+ stopped.withLock { $0 = true }
}
enum Error: Swift.Error {