Socket library built with Swift Concurrency

Since we aren't bound to a single thread, we have a global loop that continuously polls for all sockets, with a .medium priority and 0.1s interval. This is mainly for getting notifications for the socket closing or hanging up, or if new data is available. When you read or write, we don't rely on the background polling, but directly poll inline, assuming the scheduler has resources to do so (every await is a potential suspension point, if the Thread is not being using by another task, then it won't suspend). If for some reason the socket is not ready for read or write, then we sleep at a 0.01s interval and priority of the current task. These intervals are configurable via Socket.configuration. In the scenario of a using a Bluetooth socket on Linux with a CLI interface (or GUI), on a CPU with 4 cores, the first thread will be used for the CLI (ArgumentParser) and the second thread would be used exclusively for the Bluetooth Host Controller interface communication. Since you have a single long lived socket to the Linux Bluetooth subsystem, sending commands to the HCI hardware and waiting on responses should be able to be done with minimal suspension, reducing the Concurrency runtime overhead. In fact the only time I can thing of the runtime "giving up" the thread would be when sleeping for responses, and even then we are talking about sending less than 256 bytes to the kernel per command. Bluetooth LE's default MTU is a mere 23 bytes, and max is 512. In this scenario, this Socket interface would be able to issue the write and read command immediately without suspension, queuing, runloops, or switching threads. I see that a huge benefit over even CFSocket.

1 Like