ios – Learn how to make sysctl and gettimeofday thread-safe in Swift?


I am trying to sync the ntp time from the server using Kronos library.
However, I believe the code is not fully protected from multithreading access since it is using low level system code.
So, does anyone know how can I ensure sysctl and gettimeofday are thread-safe when calling them? Or, is there any thread-safe alternative to get the same result?

func currentTime() -> TimeInterval {
    var current = timeval()
    let systemTimeError = gettimeofday(&current, nil) != 0
    assert(!systemTimeError, "system clock error: system time unavailable")

    return Double(current.tv_sec) + Double(current.tv_usec) / 1_000_000
}
static func systemUptime() -> TimeInterval {
        var mib = [CTL_KERN, KERN_BOOTTIME]
        var size = MemoryLayout<timeval>.stride
        var bootTime = timeval()

        let bootTimeError = sysctl(&mib, u_int(mib.count), &bootTime, &size, nil, 0) != 0
        assert(!bootTimeError, "system clock error: kernel boot time unavailable")

        let now = currentTime()
        let uptime = Double(bootTime.tv_sec) + Double(bootTime.tv_usec) / 1_000_000
        assert(now >= uptime, "inconsistent clock state: system time precedes boot time")

        return now - uptime
    }

I have thought of using NSLock but I can only protect from the getter (caller) not the setter (system)

Leave a Reply

Your email address will not be published. Required fields are marked *