首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSThread苏醒了

NSThread苏醒了
EN

Stack Overflow用户
提问于 2014-09-19 13:14:41
回答 2查看 342关注 0票数 0

我想知道如何在objective-c中实现以下内容,

我使用串行通信与FTDI232R调制解调器进行通信,因此我使用POSIX打开、写入和读取调制解调器的路径(dev/tty/nameOfModem)。POSIX调用是同步调用,所以当读取时,我不想阻塞我的主线程,因此我考虑在单独的线程中执行读取调用。

我不希望这个辅助线程连续运行,而是仅在有要读取的内容时才唤醒,并且在读取完成后它应该处于休眠状态。我查看了文档,阅读了有关为NSRunLoop提供输入源并将该运行循环添加到辅助线程的内容,但我不知道该如何操作。

提前感谢您的帮助。

EN

回答 2

Stack Overflow用户

发布于 2014-09-19 14:11:30

您通常有一个BOOL来指示您的运行状态,然后是一个运行到的日期。在做socket-y的事情时,我倾向于这样做:

代码语言:javascript
复制
NSDate *beforeDate = [NSDate dateWithTimeIntervalSinceNow:.1];
while (self.isActive && [[NSRunLoop currentRunLoop] runMode: NSRunLoopCommonModes beforeDate:beforeDate]) {
    beforeDate = [NSDate dateWithTimeIntervalSinceNow:.1];
}

然后,当您断开与调制解调器的连接时,您可以将isActive设置为NO,以使运行循环停止。

虽然不完全是你想要的,但你浏览一下threading with NSOperation上的苹果文档可能会很有趣。

票数 0
EN

Stack Overflow用户

发布于 2014-09-19 15:01:09

为此,您可能应该使用GCD dispatch sources。下面是直接从文章中复制出来示例代码:

代码语言:javascript
复制
dispatch_source_t ProcessContentsOfFile(const char* filename)
{
   // Prepare the file for reading.
   int fd = open(filename, O_RDONLY);
   if (fd == -1)
      return NULL;
   fcntl(fd, F_SETFL, O_NONBLOCK);  // Avoid blocking the read operation

   dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
   dispatch_source_t readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ,
                                   fd, 0, queue);
   if (!readSource)
   {
      close(fd);
      return NULL;
   }

   // Install the event handler
   dispatch_source_set_event_handler(readSource, ^{
      size_t estimated = dispatch_source_get_data(readSource) + 1;
      // Read the data into a text buffer.
      char* buffer = (char*)malloc(estimated);
      if (buffer)
      {
         ssize_t actual = read(fd, buffer, (estimated));
         Boolean done = MyProcessFileData(buffer, actual);  // Process the data.

         // Release the buffer when done.
         free(buffer);

         // If there is no more data, cancel the source.
         if (done)
            dispatch_source_cancel(readSource);
      }
    });

   // Install the cancellation handler
   dispatch_source_set_cancel_handler(readSource, ^{close(fd);});

   // Start reading the file.
   dispatch_resume(readSource);
   return readSource;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25926821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档