/** try to wait for the semaphore until timeout * * \return true, if the value can be decremented * false, otherweise */ bool timed_wait(struct timespec const & absolute_timeout) { dispatch_time_t timeout = dispatch_walltime(&absolute_timeout, 0); long status = dispatch_semaphore_wait(sem, timeout); return status == 0; }
int main(int argc, char* argv[]) { // interval is 1/10th of a second uint64_t interval = NSEC_PER_SEC / 10; // for 25 seconds struct timeval now_tv; struct timespec now_ts; interval_d = (double)interval / (double)NSEC_PER_SEC; target = (unsigned int)(25 / interval_d); test_start("Timer drift test"); timeBeginPeriod(1); timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); test_ptr_notnull("DISPATCH_SOURCE_TYPE_TIMER", timer); dispatch_source_set_event_handler_f(timer, timer_handler); gettimeofday(&now_tv, NULL); now_ts.tv_sec = now_tv.tv_sec; now_ts.tv_nsec = now_tv.tv_usec * NSEC_PER_USEC; dispatch_source_set_timer(timer, dispatch_walltime(&now_ts, interval), interval, 0); dispatch_resume(as_do(timer)); dispatch_main(); return 0; }
static inline dispatch_time_t rb_num2timeout(VALUE num) { dispatch_time_t dispatch_timeout = DISPATCH_TIME_FOREVER; if (!NIL_P(num)) { const double sec = rb_num2dbl(num); if (sec < TIMEOUT_MAX) { dispatch_timeout = dispatch_walltime(NULL, SEC2NSEC_INT64(sec)); } } return dispatch_timeout; }
static void reschedule_timer(void) { const struct heim_event_data *e = heap_head(timer_heap); if (e == NULL) { /* * if there are no more events, cancel timer by setting timer * to forever, later calls will pull it down to !forever when * needed again */ dispatch_source_set_timer(timer_source, DISPATCH_TIME_FOREVER, 0, 10ull * NSEC_PER_SEC); } else { struct timespec ts; ts.tv_sec = e->t; ts.tv_nsec = 0; dispatch_source_set_timer(timer_source, dispatch_walltime(&ts, 0), 0, 10ull * NSEC_PER_SEC); } }