@eskimo @endecotp Sorry for the misunderstanding!
Some APIs are atomic, that is, they can be called from any thread at any time but they are still subject to races.
Is there a way that I can prevent the race condition that you mentioned here?
After some researches, I have found the Objective-C code posted in StackOverFlow that claims to prevent the race condition when getting up time.
Link: https://stackoverflow.com/a/40497811
I have converted it to Swift below, is it true that the code below can prevent the race condition?
static func systemUptime() -> TimeInterval {
var now: TimeInterval
var beforeNow: Double
var afterNow = bootTime()
var i = 0
repeat {
assert(i < 10, "systemUpTime loop repeats more than 10 times")
beforeNow = afterNow
now = currentTime()
afterNow = bootTime()
i += 1
} while (afterNow != beforeNow)
assert(now >= beforeNow, "inconsistent clock state: system time precedes boot time")
return now - beforeNow
}
private static func bootTime() -> Double {
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")
return Double(bootTime.tv_sec) + Double(bootTime.tv_usec) / 1_000_000
}
func currentTime() -> TimeInterval {
var current = timeval()
let systemTimeError = gettimeofday(¤t, nil) != 0
assert(!systemTimeError, "system clock error: system time unavailable")
return Double(current.tv_sec) + Double(current.tv_usec) / 1_000_000
}