代码之家  ›  专栏  ›  技术社区  ›  Era

GCD和运行循环

  •  2
  • Era  · 技术社区  · 14 年前

    在我的应用程序中,我添加了一个 (通过 CFMachPortCreateRunLoopSource源 CFRunLoop循环

    n线程 并添加创建的 CFRunLoopSourceRef文件 到它的运行循环通过 CFRunLoopAddSource源

    更新


    到目前为止,我已经知道了这一点,但是既没有调用事件tap的回调函数,也没有调用dispatch\ source\ event\ handler块。有什么想法吗?

    CFMachPortRef port = CGEventTapCreate(kCGSessionEventTap,
                                          kCGHeadInsertEventTap,
                                          opts,
                                          desc_.eventMask,
                                          _CGEventCallback,
                                          self);
    
    // create dispatch source
    dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV,
                                                      CFMachPortGetPort(port),
                                                      0,
                                                      dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
    
    // set event handler
    dispatch_source_set_event_handler(source, ^{
        printf("handle me!\n");
    });
    
    dispatch_resume(source);
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   Brian Webster    14 年前

    实际上,你可以使用GCD来监视Mach端口,使用 dispatch_source_create() 功能。代码如下所示:

    mach_port_t myPort; //assume you have this already
    dispatch_source_t portSource;
    
    portSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, myPort, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT));
    dispatch_source_set_event_handler(portSource, ^(void) { //code for handling incoming message here });
    
    dispatch_resume(portSource);
    

        2
  •  0
  •   James    8 年前

    要计划GCD队列上通知端口的回调,可以使用 IONotificationPortSetDispatchQueue CFRunLoopAddSource 使用Runloop。

    例子:

    IOServiceOpen(driver, mach_task_self(), 0, &connection);
    
    notifyPort = IONotificationPortCreate(kIOMasterPortDefault);
    
    IOServiceAddInterestNotification(
      notifyPort,
      driver,
      kIOGeneralInterest,
      myCallback,
      NULL, //refcon
      &notificationObject
    );
    
    // Instead of this:
    // CFRunLoopAddSource(CFRunLoopGetCurrent(),
    //                    IONotificationPortGetRunLoopSource(notifyPort),
    //                    kCFRunLoopDefaultMode);
    // do this:
    IONotificationPortSetDispatchQueue(notifyPort, myQueue);
    

    myCallback() myQueue .

        3
  •  0
  •   popipo    4 年前

    dispatch_resume 方法必须位于调用 mach_msg port . 你可以试试。