Objective-C runtime 拾遗 (四)—— 不常用的进程/线程通信方法

童威
• 阅读 6346

前段时间在写Promise时,调研了iOS有哪些通信的方法。delegate,notification,GCD是常见的方法,除此之外还有一些方法,在此记录共享一下。

NSPipe

官方这样解释:

NSPipe objects provide an object-oriented interface for accessing pipes. An NSPipe object represents both ends of a pipe and enables communication through the pipe. A pipe is a one-way communications channel between related processes; one process writes data, while the other process reads that data. The data that passes through the pipe is buffered; the size of the buffer is determined by the underlying operating system. NSPipe is an abstract class, the public interface of a class cluster.

表示一个可以单向通信的对象,只能一端读一端写。

NSPipe很简单,就两个属性:

@property (readonly, retain) NSFileHandle *fileHandleForReading;
@property (readonly, retain) NSFileHandle *fileHandleForWriting;

跟上文表述一致。具体看这个例子吧,idea很赞。iOS IO 重定向(NSLog to UITextView)

NSPipe还可以用在socket中。NSPipe用作通信时,只能传递流式的数据。NSPipe通过文件是可以跨进程通信的。

信号量

dispatch_semaphore常用作生产消费者模型中,是GCD中用来做并发控制的。虽然不常见,但的确是可以通过dispatch_semaphore_create dispatch_semaphore_signal dispatch_semaphore_wait这几个方法来进行通信。

资料很多,随便搜。
遗憾的是,参数传递是个问题,而且用作线程间的通信也很牵强,会让代码难于理解。

NSPort

NSPort是一个通信的通道,通过NSPortMessage来传送消息

  • 例子

- (void) foo {
  NSPort *port = [NSMachPort port];
  port.delegate = self;

  [[NSRunLoop currentRunLoop] addPort:port forMode:NSDefaultRunLoopMode];

  SomeOtherWorker *worker = [[SomeOtherWorker alloc] init];
  [NSThread detachNewThreadSelector:@selector(launchWithPort:)
                             toTarget:worker
                           withObject:port];
}

- (void)handlePortMessage:(NSMessagePort*)message{
    NSUInteger msgId = [[message valueForKeyPath:@"msgid"] integerValue]; //[message msgid]
    NSPort *localPort = [message valueForKeyPath:@"localPort"];//[message receivePort]
    NSPort *remotePort = [message valueForKeyPath:@"remotePort"]//[message sendPort];
    ......
}

Worker Class

@implementation SomeOtherWorker
{
    NSPort* _remotePort;
    NSPort* _myPort;
}

- (void)launchWithPort:(NSPort *)port {
    _remotePort = port;
    [[NSThread currentThread] setName:@"SomeOtherThread"];
    [[NSRunLoop currentRunLoop] run];

    _myPort = [NSMachPort port];
    _myPort.delegate = self;

    [[NSRunLoop currentRunLoop] addPort:_myPort forMode:NSDefaultRunLoopMode];
    [_remotePort sendBeforeDate:[NSDate date]
                         msgid:kMsg1
                    components:nil
                          from:_myPort
                      reserved:0];
}

#pragma mark - NSPortDelegate 如不接收父线程的消息,则不用实现
- (void)handlePortMessage:(NSPortMessage *)message
{
}
@end
  • 要注意的
    NSPort能传递msgidcomponentsmsgid是一个uint,而components是这样说的:

The data to send in the message. components should contain only NSData and NSPort objects, and the contents of the NSData objects should be in network byte order.

运行时发现如果传NSData的话,拿到是个OS_dispatch_data类型的实例。暂时不太懂。

CF的使用方法参考这里

其他参考

mmap 共享文件

严格来讲mmap不算是一种通信方式。

mmap is a POSIX-compliant Unix system call that maps files or devices into memory.

在越狱机上可以通过mmap共享内存。但非越狱有沙盒,文件共享只能通过App Group。暂时没有试过,先欠着,以后写demo吧。

参考

XPC Service

Creating XPC Services 讲得很详细了

XPC(和翻译)也讲得很不错。

需要注意的是上述文章提到了:

错误隔离 (Fault Isolation) 和 权限隔离 (Split Privileges)

这是App架构设计的重要准则之一。

XPC 是跨进程的。iOS上无法使用,除非越狱。

参考

http://blog.csdn.net/yxh265/a...
https://github.com/stevestrez...
http://aron.cedercrantz.com/2...
https://github.com/a1anyip/li...
https://github.com/nevyn/Mesh...
http://blog.csdn.net/jia12216...
https://segmentfault.com/a/11...
http://www.tanhao.me/pieces/6...

原作写于segmentfault 链接

点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
4年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
4年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
4年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
4年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
4年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
可莉 可莉
4年前
10分钟教你用Python爬取Baidu文库全格式内容
!(https://oscimg.oschina.net/oscnet/fe00aeba4aa8e2873e2a4a18a4066315c38.jpg)程序猿声代码黑科技的分享区!(https://oscimg.oschina.net/oscnet/de84f57eed4cea63681fd0aaf5b5b95fb44.g
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
2年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
童威
童威
Lv1
春色边城动,客思故乡来。
文章
4
粉丝
0
获赞
0