static int _gcdpoll_watch_add(AvahiWatch *w, AvahiWatchEvent a_events) { dispatch_source_t sr = NULL; dispatch_source_t sw = NULL; if ((a_events & AVAHI_WATCH_IN) && !w->w_read) { sr = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, w->fd, 0, mdns_sq); if (!sr) return -1; dispatch_set_context(sr, w); dispatch_source_set_event_handler_f(sr, gcdpollcb_watch_read); } if ((a_events & AVAHI_WATCH_OUT) && !w->w_write) { sw = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, w->fd, 0, mdns_sq); if (!sw) { if (sr) { dispatch_source_cancel(sr); dispatch_release(sr); } return -1; } dispatch_set_context(sw, w); dispatch_source_set_event_handler_f(sw, gcdpollcb_watch_write); } if (sr) { w->w_read = sr; dispatch_resume(sr); } if (sw) { w->w_write = sw; dispatch_resume(sw); } return 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; }
void test_timer(void) { dispatch_test_start("Dispatch Update Timer"); dispatch_queue_t main_q = dispatch_get_main_queue(); //test_ptr("dispatch_get_main_queue", main_q, dispatch_get_current_queue()); __block int i = 0; struct timeval start_time; gettimeofday(&start_time, NULL); dispatch_source_t s = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, main_q); test_ptr_notnull("dispatch_source_create", s); dispatch_source_set_timer(s, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), NSEC_PER_SEC, 0); dispatch_source_set_cancel_handler(s, ^{ struct timeval end_time; gettimeofday(&end_time, NULL); // Make sure we actually managed to adjust the interval // duration. Seven one second ticks would blow past // this. test_long_less_than("total duration", end_time.tv_sec - start_time.tv_sec, 3); test_stop(); dispatch_release(s); });
void WebProcess::platformInitializeWebProcess(const WebProcessCreationParameters& parameters, CoreIPC::MessageDecoder&) { m_networkAccessManager = new QtNetworkAccessManager(this); ASSERT(!parameters.cookieStorageDirectory.isEmpty() && !parameters.cookieStorageDirectory.isNull()); WebCore::SharedCookieJarQt* jar = WebCore::SharedCookieJarQt::create(parameters.cookieStorageDirectory); m_networkAccessManager->setCookieJar(jar); // Do not let QNetworkAccessManager delete the jar. jar->setParent(0); ASSERT(!parameters.diskCacheDirectory.isEmpty() && !parameters.diskCacheDirectory.isNull()); QNetworkDiskCache* diskCache = new QNetworkDiskCache(); diskCache->setCacheDirectory(parameters.diskCacheDirectory); // The m_networkAccessManager takes ownership of the diskCache object upon the following call. m_networkAccessManager->setCache(diskCache); #if defined(Q_OS_MACX) pid_t ppid = getppid(); dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, ppid, DISPATCH_PROC_EXIT, queue); if (source) { dispatch_source_set_event_handler_f(source, parentProcessDiedCallback); dispatch_resume(source); } #endif WebCore::RuntimeEnabledFeatures::setSpeechInputEnabled(false); // We'll only install the Qt builtin bundle if we don't have one given by the UI process. // Currently only WTR provides its own bundle. if (parameters.injectedBundlePath.isEmpty()) { m_injectedBundle = InjectedBundle::create(String()); m_injectedBundle->setSandboxExtension(SandboxExtension::create(parameters.injectedBundlePathExtensionHandle)); QtBuiltinBundle::shared().initialize(toAPI(m_injectedBundle.get())); } }
void WorkQueue::registerMachPortEventHandler(mach_port_t machPort, MachPortEventType eventType, const Function<void()>& function) { ASSERT(machPort != MACH_PORT_NULL); dispatch_source_type_t sourceType = 0; switch (eventType) { case MachPortDataAvailable: sourceType = DISPATCH_SOURCE_TYPE_MACH_RECV; break; case MachPortDeadNameNotification: sourceType = DISPATCH_SOURCE_TYPE_MACH_SEND; break; } dispatch_source_t dispatchSource = dispatch_source_create(sourceType, machPort, 0, m_dispatchQueue); EventSource* eventSource = new EventSource(eventType, dispatchSource, function); dispatch_set_context(dispatchSource, eventSource); dispatch_source_set_event_handler_f(dispatchSource, &EventSource::eventHandler); dispatch_source_set_cancel_handler_f(dispatchSource, &EventSource::cancelHandler); dispatch_set_finalizer_f(dispatchSource, &EventSource::finalizeHandler); // Add the source to our set of sources. { MutexLocker locker(m_eventSourcesMutex); ASSERT(!m_eventSources.contains(machPort)); m_eventSources.set(machPort, eventSource); // And start it! dispatch_resume(dispatchSource); } }
static void test_io_close(int with_timer, bool from_path) { #define chunks 4 #define READSIZE (512*1024) unsigned int i; const char *path = LARGE_FILE; int fd = open(path, O_RDONLY); if (fd == -1) { if (errno == ENOENT) { test_skip("Large file not found"); return; } test_errno("open", errno, 0); test_stop(); } #ifdef F_GLOBAL_NOCACHE if (fcntl(fd, F_GLOBAL_NOCACHE, 1) == -1) { test_errno("fcntl F_GLOBAL_NOCACHE", errno, 0); test_stop(); } #endif struct stat sb; if (fstat(fd, &sb)) { test_errno("fstat", errno, 0); test_stop(); } const size_t size = (size_t)sb.st_size / chunks; const int expected_error = with_timer? ECANCELED : 0; dispatch_source_t t = NULL; dispatch_group_t g = dispatch_group_create(); dispatch_group_enter(g); void (^cleanup_handler)(int error) = ^(int error) { test_errno("create error", error, 0); dispatch_group_leave(g); close(fd); }; dispatch_io_t io; if (!from_path) { io = dispatch_io_create(DISPATCH_IO_RANDOM, fd, dispatch_get_global_queue(0, 0), cleanup_handler); } else { #if DISPATCHTEST_IO_PATH io = dispatch_io_create_with_path(DISPATCH_IO_RANDOM, path, O_RDONLY, 0, dispatch_get_global_queue(0, 0), cleanup_handler); #endif } dispatch_io_set_high_water(io, READSIZE); if (with_timer == 1) { dispatch_io_set_low_water(io, READSIZE); dispatch_io_set_interval(io, 2 * NSEC_PER_SEC, DISPATCH_IO_STRICT_INTERVAL); } else if (with_timer == 2) { t = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0,0)); dispatch_retain(io); dispatch_source_set_event_handler(t, ^{ dispatch_io_close(io, DISPATCH_IO_STOP); dispatch_source_cancel(t); });
void RequestTimer::setTimeout(int seconds) { m_timeoutSeconds = seconds > 0 ? seconds : 0; cancelTimerSource(); if (!m_timeoutSeconds) { return; } dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); m_timerSource = dispatch_source_create( DISPATCH_SOURCE_TYPE_TIMER, 0, DISPATCH_TIMER_STRICT, q); dispatch_time_t t = dispatch_time(DISPATCH_TIME_NOW, m_timeoutSeconds * NSEC_PER_SEC); dispatch_source_set_timer(m_timerSource, t, DISPATCH_TIME_FOREVER, 0); // Use the timer group as a semaphore. When the source is cancelled, // libdispatch will make sure all pending event handlers have finished before // invoking the cancel handler. This means that if we cancel the source and // then wait on the timer group, when we are done waiting, we know the source // is completely done and it's safe to free memory (e.g., in the destructor). // See cancelTimerSource() above. dispatch_group_enter(m_timerGroup); dispatch_source_set_event_handler(m_timerSource, ^{ onTimeout(); // Cancelling ourselves isn't needed for correctness, but we can go ahead // and do it now instead of waiting on it later, so why not. (Also, // getRemainingTime does use this opportunistically, but it's best effort.) dispatch_source_cancel(m_timerSource); });
static VALUE rb_source_init(VALUE self, SEL sel, VALUE type, VALUE handle, VALUE mask, VALUE queue) { Check_Queue(queue); rb_source_t *src = RSource(self); src->source_enum = (source_enum_t) NUM2LONG(type); dispatch_source_type_t c_type = rb_source_enum2type(src->source_enum); assert(c_type != NULL); uintptr_t c_handle = NUM2UINT(rb_Integer(handle)); unsigned long c_mask = NUM2LONG(mask); dispatch_queue_t c_queue = RQueue(queue)->queue; src->source = dispatch_source_create(c_type, c_handle, c_mask, c_queue); assert(src->source != NULL); rb_vm_block_t *block = get_prepared_block(); GC_WB(&src->event_handler, block); GC_RETAIN(self); // apparently needed to ensure consistent counting dispatch_set_context(src->source, (void *)self); dispatch_source_set_event_handler_f(src->source, rb_source_event_handler); GC_WB(&src->handle, handle); if (rb_source_is_file(src) && rb_obj_is_kind_of(handle, rb_cIO)) { dispatch_source_set_cancel_handler_f(src->source, rb_source_close_handler); } rb_dispatch_resume(self, 0); return self; }
/* Called when a new client connects */ BOOL mf_peer_init(freerdp_peer* client) { client->ContextSize = sizeof(mfPeerContext); client->ContextNew = (psPeerContextNew) mf_peer_context_new; client->ContextFree = (psPeerContextFree) mf_peer_context_free; if (!freerdp_peer_context_new(client)) return FALSE; info_event_queue = mf_event_queue_new(); info_queue = dispatch_queue_create("FreeRDP.update.timer", DISPATCH_QUEUE_SERIAL); info_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, info_queue); if(info_timer) { //DEBUG_WARN( "created timer\n"); dispatch_source_set_timer(info_timer, DISPATCH_TIME_NOW, 42ull * NSEC_PER_MSEC, 100ull * NSEC_PER_MSEC); dispatch_source_set_event_handler(info_timer, ^{ //DEBUG_WARN( "dispatch\n"); mfEvent* event = mf_event_new(MF_EVENT_TYPE_FRAME_TICK); mf_event_push(info_event_queue, (mfEvent*) event);} ); dispatch_resume(info_timer); }
dispatch_source_t create_source(dispatch_source_type_t type, int socket, int action) { log_detail("make source socket %d action %s\n", socket, action_name(action)); dispatch_source_t source = dispatch_source_create(type, socket, 0, queue); dispatch_source_set_event_handler(source, ^{ log_detail("source event socket %d action %s\n", socket, action_name(action)); curl_perform_action(socket, action); });
DispatchSource createSourceTimer(void * ctx, dispatch_function_t handler) { dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, DISPATCH_TARGET_QUEUE_DEFAULT); dispatch_set_context(source, ctx); dispatch_source_set_event_handler_f(source, handler); dispatch_resume(source); return DispatchSource(source); }
DispatchSource createSourceSignal(int sig, void * ctx, dispatch_function_t handler) { signal(sig, SIG_IGN); dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, sig, 0, DISPATCH_TARGET_QUEUE_DEFAULT); dispatch_set_context(source, ctx); dispatch_source_set_event_handler_f(source, handler); dispatch_resume(source); return DispatchSource(source); }
int OSMemoryNotificationTimedWait(OSMemoryNotificationRef note, OSMemoryNotificationLevel *level, const struct timeval *abstime) { dispatch_semaphore_t sema = dispatch_semaphore_create(0); dispatch_retain(sema); dispatch_source_t memoryNotificationSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_VM, 0, DISPATCH_VM_PRESSURE, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); dispatch_source_set_event_handler(memoryNotificationSource, ^{ dispatch_semaphore_signal(sema); dispatch_release(sema); });
static void init_globals(void) { static dispatch_once_t once; dispatch_once(&once, ^{ timerq = dispatch_queue_create("hiem-sipc-timer-q", NULL); timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timerq); dispatch_source_set_event_handler(timer, ^{ timer_ev(); } ); workq = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); eventq = dispatch_queue_create("heim-ipc.event-queue", NULL); });
int main(void) { const char *path = "/usr/share/dict/words"; struct stat sb; dispatch_test_start("Dispatch Source Read"); int infd = open(path, O_RDONLY); if (infd == -1) { perror(path); exit(EXIT_FAILURE); } if (fstat(infd, &sb) == -1) { perror(path); exit(EXIT_FAILURE); } bytes_total = sb.st_size; if (fcntl(infd, F_SETFL, O_NONBLOCK) != 0) { perror(path); exit(EXIT_FAILURE); } if (!dispatch_test_check_evfilt_read_for_fd(infd)) { test_skip("EVFILT_READ kevent not firing for test file"); test_fin(NULL); } dispatch_queue_t main_q = dispatch_get_main_queue(); test_ptr_notnull("dispatch_get_main_queue", main_q); dispatch_source_t reader = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, infd, 0, main_q); test_ptr_notnull("dispatch_source_create", reader); assert(reader); dispatch_source_set_event_handler(reader, ^{ size_t estimated = dispatch_source_get_data(reader); fprintf(stderr, "bytes available: %zu\n", estimated); test_double_less_than_or_equal("estimated", estimated, bytes_total - bytes_read); const ssize_t bufsiz = 1024*500; // 500 KB buffer static char buffer[1024*500]; // 500 KB buffer ssize_t actual = read(infd, buffer, sizeof(buffer)); bytes_read += actual; printf("bytes read: %zd\n", actual); if (actual < bufsiz) { actual = read(infd, buffer, sizeof(buffer)); bytes_read += actual; // confirm EOF condition test_long("EOF", actual, 0); dispatch_source_cancel(reader); } });
void test_proc(pid_t bad_pid) { dispatch_source_t proc_s[PID_CNT], proc; int res; pid_t pid, monitor_pid; event_cnt = 0; // Creates a process and register multiple observers. Send a signal, // exit the process, etc., and verify all observers were notified. posix_spawnattr_t attr; res = posix_spawnattr_init(&attr); assert(res == 0); #if HAVE_DECL_POSIX_SPAWN_START_SUSPENDED res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_START_SUSPENDED); assert(res == 0); #endif char* args[] = { "/bin/sleep", "2", NULL }; res = posix_spawnp(&pid, args[0], NULL, &attr, args, NULL); if (res < 0) { perror(args[0]); exit(127); } res = posix_spawnattr_destroy(&attr); assert(res == 0); dispatch_group_t group = dispatch_group_create(); assert(pid > 0); monitor_pid = bad_pid ? bad_pid : pid; // rdar://problem/8090801 int i; for (i = 0; i < PID_CNT; ++i) { dispatch_group_enter(group); proc = proc_s[i] = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, monitor_pid, DISPATCH_PROC_EXIT, dispatch_get_global_queue(0, 0)); test_ptr_notnull("dispatch_source_proc_create", proc); dispatch_source_set_event_handler(proc, ^{ long flags = dispatch_source_get_data(proc); test_long("DISPATCH_PROC_EXIT", flags, DISPATCH_PROC_EXIT); event_cnt++; dispatch_source_cancel(proc); }); dispatch_source_set_cancel_handler(proc, ^{ dispatch_group_leave(group); });
static void resumeAudio(struct nodeInstanceData *context, VuoOutputTrigger(decodedAudio, VuoList_VuoAudioSamples)) { /* audio queue */ if( VuoMovie_containsAudio(context->movie) && context->playbackRate == 1.) { dispatch_queue_t a_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); context->audio_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, a_queue); // audio (plays at a steady rate) dispatch_source_set_timer(context->audio_timer, DISPATCH_TIME_NOW, DISPATCH_TIME_FOREVER, 0); dispatch_source_set_event_handler(context->audio_timer, ^{ playNextAudioFrame(context, decodedAudio); });
static void onSocketAccept() { if( ! listener ) return; SocketClientRef client = calloc(1, sizeof(SocketClient)); assert(client); socklen_t len = sizeof(client->addr); client->fd = accept(listener->fd, (struct sockaddr *)&client->addr, &len); dispatch_queue_t queue = dispatch_queue_create("ru.n3b.SocketReadQueue", NULL); client->source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, (uintptr_t) client->fd, 0, queue); dispatch_source_set_event_handler(client->source, ^{ onSocketDataReceived(client, dispatch_source_get_data(client->source)); });
static void setRepeatingTimer(struct nodeInstanceData *ctx, const VuoReal seconds, VuoOutputTrigger(fired,VuoInteger)) { if (ctx->timer) cancelRepeatingTimer(ctx); dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); ctx->timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, q); uint64_t nanoseconds = seconds * NSEC_PER_SEC; dispatch_source_set_timer(ctx->timer, dispatch_time(DISPATCH_TIME_NOW, nanoseconds), nanoseconds, 0); dispatch_source_set_event_handler(ctx->timer, ^{ fired(++ctx->eventCount); });
static void child_tty_client(void) { dispatch_source_t src; char buf[16] = ""; ssize_t bytes_wr; src = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, (uintptr_t)STDIN_FILENO, 0, NULL); if (!src) { exit(1); } dispatch_source_set_event_handler(src, ^{});
/****************************************************************************** * _kextmanager_lock_volume tries to lock volumes for clients (kextutil) *****************************************************************************/ kern_return_t _kextmanager_lock_kextload( mach_port_t server, mach_port_t client, int * lockstatus) { kern_return_t mig_result = KERN_FAILURE; int result; if (!lockstatus) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogIPCFlag, "kextmanager_lock_kextload requires non-NULL lockstatus."); mig_result = KERN_SUCCESS; result = EINVAL; goto finish; } if (gClientUID != 0) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel, "Non-root process doesn't need to lock as it will fail to load."); mig_result = KERN_SUCCESS; result = EPERM; goto finish; } if (_gKextutilLock) { mig_result = KERN_SUCCESS; result = EBUSY; goto finish; } result = ENOMEM; _gKextutilLock = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_SEND, client, DISPATCH_MACH_SEND_DEAD, dispatch_get_main_queue()); if (_gKextutilLock) { dispatch_source_set_event_handler(_gKextutilLock, ^{ OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogIPCFlag, "Client exited without releasing kextutil lock."); removeKextutilLock(); }); dispatch_source_set_cancel_handler(_gKextutilLock, ^{ dispatch_release(_gKextutilLock); mach_port_deallocate(mach_task_self(), client); _gKextutilLock = NULL; });
static dispatch_source_t mach_create_client_source(xpc_port_t port, void *context, dispatch_queue_t tq) { mach_port_t mp = (mach_port_t)port; dispatch_source_t ret; ret = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, (uintptr_t)mp, 0, tq); dispatch_set_context(ret, context); dispatch_source_set_event_handler_f(ret, xpc_connection_recv_message); dispatch_source_set_cancel_handler(ret, ^{ xpc_connection_destroy_peer(dispatch_get_context(ret)); });
static void retry_timer(void) { dispatch_source_t s; dispatch_time_t t; s = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, g_queue); t = dispatch_time(DISPATCH_TIME_NOW, 5ull * NSEC_PER_SEC); dispatch_source_set_timer(s, t, 0, NSEC_PER_SEC); dispatch_source_set_event_handler(s, ^{ create_dns_sd(); dispatch_release(s); });
static void setRepeatingTimer(struct nodeInstanceData *ctx, const VuoReal seconds, VuoOutputTrigger(fired,void)) { cancelRepeatingTimer(ctx); if (seconds <= 0) return; dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); ctx->timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, q); uint64_t nanoseconds = (seconds > 0.001 ? (seconds * NSEC_PER_SEC) : (NSEC_PER_SEC / 1000)); dispatch_source_set_timer(ctx->timer, dispatch_time(DISPATCH_TIME_NOW, nanoseconds), nanoseconds, 0); dispatch_source_set_event_handler(ctx->timer, ^{ fired(); });
void IOHIDEventSystemStatistics::scheduleWithDispatchQueue(dispatch_queue_t queue) { _dispatch_queue = queue; if ( _dispatch_queue ) { _pending_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)); dispatch_set_context(_pending_source, this); dispatch_source_set_event_handler_f(_pending_source, IOHIDEventSystemStatistics::handlePendingStats); dispatch_resume(_pending_source); notify_register_dispatch( "com.apple.iokit.hid.displayStatus", &_displayToken,_dispatch_queue, ^(__unused int token){ notify_get_state(_displayToken, &_displayState); }); }
/* Return true, iff we didn't schedule any work, return false if we did. */ bool asynchttp_request(CFHTTPMessageRef request, asynchttp_t *http) { secdebug("http", "request %@", request); if (request) { http->request = request; CFRetain(request); } /* Create the stream for the request. */ require_quiet(http->stream = CFReadStreamCreateForHTTPRequest( kCFAllocatorDefault, http->request), errOut); /* Set a reasonable timeout */ require_quiet(http->timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, http->queue), errOut); dispatch_source_set_event_handler(http->timer, ^{ asynchttp_timer_proc(http); });
static int _gcdpoll_timeout_add(AvahiTimeout *t, const struct timeval *tv) { struct timeval e_tv; struct timeval now; int64_t nsecs; int ret; ret = gettimeofday(&now, NULL); if (ret != 0) return -1; if (!t->timer) { t->timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, mdns_sq); if (!t->timer) return -1; dispatch_set_context(t->timer, t); dispatch_source_set_event_handler_f(t->timer, gcdpollcb_timer); } else dispatch_suspend(t->timer); if ((tv->tv_sec == 0) && (tv->tv_usec == 0)) { dispatch_source_set_timer(t->timer, DISPATCH_TIME_NOW, DISPATCH_TIME_FOREVER /* one-shot */, 0); } else { timersub(tv, &now, &e_tv); nsecs = e_tv.tv_sec * NSEC_PER_SEC + e_tv.tv_usec * 1000; dispatch_source_set_timer(t->timer, dispatch_time(DISPATCH_TIME_NOW, nsecs), DISPATCH_TIME_FOREVER /* one-shot */, 0); } dispatch_resume(t->timer); return 0; }
static void retry_timer(void) { dispatch_time_t t; heim_assert(g_dnsRef == NULL, "called create when a connection already existed"); if (g_restart_timer) return; g_restart_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, g_queue); t = dispatch_time(DISPATCH_TIME_NOW, 5ull * NSEC_PER_SEC); dispatch_source_set_timer(g_restart_timer, t, 0, NSEC_PER_SEC); dispatch_source_set_event_handler(g_restart_timer, ^{ create_dns_sd(); dispatch_release(g_restart_timer); g_restart_timer = NULL; });
void test_short_timer(void) { // Add a large number of timers with suspended target queue in front of // the timer being measured <rdar://problem/7401353> g = dispatch_group_create(); q = dispatch_queue_create("q", NULL); int i; for (i = 0; i < N; i++) { t[i] = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, q); dispatch_source_set_timer(t[i], DISPATCH_TIME_NOW, interval, 0); dispatch_group_enter(g); dispatch_source_set_registration_handler(t[i], ^{ dispatch_suspend(t[i]); dispatch_group_leave(g); }); dispatch_resume(t[i]); }
void test_timer(void) { dispatch_test_start("Dispatch Source Timer, bit 31"); dispatch_queue_t main_q = dispatch_get_main_queue(); //test_ptr("dispatch_get_main_queue", main_q, dispatch_get_current_queue()); struct timeval start_time; static dispatch_source_t s; s = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, main_q); test_ptr_notnull("dispatch_source_create", s); dispatch_source_set_timer(s, dispatch_time(DISPATCH_TIME_NOW, 0x80000000ull), 0x80000000ull, 0); gettimeofday(&start_time, NULL); dispatch_source_set_event_handler(s, ^{ dispatch_source_cancel(s); });