我想知道如何在objective-c中实现以下内容,
我使用串行通信与FTDI232R调制解调器进行通信,因此我使用POSIX打开、写入和读取调制解调器的路径(dev/tty/nameOfModem)。POSIX调用是同步调用,所以当读取时,我不想阻塞我的主线程,因此我考虑在单独的线程中执行读取调用。
我不希望这个辅助线程连续运行,而是仅在有要读取的内容时才唤醒,并且在读取完成后它应该处于休眠状态。我查看了文档,阅读了有关为NSRunLoop提供输入源并将该运行循环添加到辅助线程的内容,但我不知道该如何操作。
提前感谢您的帮助。
发布于 2014-09-19 14:11:30
您通常有一个BOOL来指示您的运行状态,然后是一个运行到的日期。在做socket-y的事情时,我倾向于这样做:
NSDate *beforeDate = [NSDate dateWithTimeIntervalSinceNow:.1];
while (self.isActive && [[NSRunLoop currentRunLoop] runMode: NSRunLoopCommonModes beforeDate:beforeDate]) {
beforeDate = [NSDate dateWithTimeIntervalSinceNow:.1];
}然后,当您断开与调制解调器的连接时,您可以将isActive设置为NO,以使运行循环停止。
虽然不完全是你想要的,但你浏览一下threading with NSOperation上的苹果文档可能会很有趣。
发布于 2014-09-19 15:01:09
为此,您可能应该使用GCD dispatch sources。下面是直接从文章中复制出来示例代码:
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;
}https://stackoverflow.com/questions/25926821
复制相似问题