iOS 多线程(六)-线程间通信

iOS 中,两个线程之间要想互相通信,可以使用:NSMachPort
示例:


#import "ViewController.h"
#import "MyWorkerClass.h"
@interface ViewController ()<NSMachPortDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor orangeColor];
    //1. 创建主线程的port
    // 子线程通过此端口发送消息给主线程
    NSPort *myPort = [NSMachPort port];
 
    //2. 设置port的代理回调对象
    myPort.delegate = self;
 
    //3. 把port加入runloop,接收port消息
    [[NSRunLoop currentRunLoop] addPort:myPort forMode:NSDefaultRunLoopMode];
 
    NSLog(@"---myport %@", myPort);
    //4. 启动次线程,并传入主线程的port
    MyWorkerClass *work = [[MyWorkerClass alloc] init];
    [NSThread detachNewThreadSelector:@selector(launchThreadWithPort:)
                             toTarget:work
                           withObject:myPort];
}

#pragma mark - NSPortDelegate
- (void)handlePortMessage:(NSMessagePort*)message{
 
    NSLog(@"接到子线程传递的消息!%@",message);
    //1. 消息id
    NSUInteger msgId = [[message valueForKeyPath:@"msgid"] integerValue];
    //2. 当前主线程的port
    NSPort *localPort = [message valueForKeyPath:@"localPort"];
    //3. 接收到消息的port(来自其他线程)
    NSPort *remotePort = [message valueForKeyPath:@"remotePort"];
 
    if (msgId == 100)
    {
        //向子线的port发送消息
        [remotePort sendBeforeDate:[NSDate date]
                             msgid:200
                        components:nil
                              from:localPort
                          reserved:0];
 
    }
}


@end

#import <Foundation/Foundation.h>

@interface MyWorkerClass : NSObject

@end


#import "MyWorkerClass.h"

@interface MyWorkerClass ()<NSMachPortDelegate> {
    NSPort *remotePort;
    NSPort *myPort;
}

@end
@implementation MyWorkerClass

- (void)launchThreadWithPort:(NSPort *)port {

   @autoreleasepool {

       //1. 保存主线程传入的port
       remotePort = port;

       //2. 设置子线程名字
       [[NSThread currentThread] setName:@"MyWorkerClassThread"];

       //3. 开启runloop
       [[NSRunLoop currentRunLoop] run];

       //4. 创建自己port
       myPort = [NSPort port];

       //5.
       myPort.delegate = self;

       //6. 将自己的port添加到runloop
       //作用1、防止runloop执行完毕之后推出
       //作用2、接收主线程发送过来的port消息
       [[NSRunLoop currentRunLoop] addPort:myPort forMode:NSDefaultRunLoopMode];

       //7. 完成向主线程port发送消息
       [self sendPortMessage];

   }
}

/**
*   完成向主线程发送port消息
*/
- (void)sendPortMessage {

   NSMutableArray *array  =[[NSMutableArray alloc]initWithArray:@[@"1",@"2"]];
   //发送消息到主线程
   [remotePort sendBeforeDate:[NSDate date]
                        msgid:100
                   components:array
                         from:myPort
                     reserved:0];

}


#pragma mark - NSPortDelegate

/**
*  接收到主线程port消息
*/
- (void)handlePortMessage:(NSPortMessage *)message
{
   NSLog(@"接收到父线程的消息...\n");

   //    unsigned int msgid = [message msgid];
   //    NSPort* distantPort = nil;
   //
   //    if (msgid == kCheckinMessage)
   //    {
   //        distantPort = [message sendPort];
   //
   //    }
   //    else if(msgid == kExitMessage)
   //    {
   //        CFRunLoopStop((__bridge CFRunLoopRef)[NSRunLoop currentRunLoop]);
   //    }
}

@end

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前言 说到多线程同步问题就不得不提多线程中的锁机制,多线程操作过程中往往多个线程是并发执行的,同一个资源可能被多个...
    進无尽阅读 1,346评论 0 12
  • 讲多线程这个话题,就免不了先了解多线程相关的技术概念。本文涉及到的技术概念有CPU、进程、线程、同异步、队列等概念...
    jackyshan阅读 3,922评论 2 26
  • 多线程原理 线程和进程的关系和区别 1、线程定义 线程是进程的基本执行单元,一个进程的所有任务都要在线程中执行 进...
    荒漠现甘泉阅读 653评论 0 1
  • 1 RunLoop简介 神秘的RunLoop。一个应用开始运行以后放在那里,如果不对它进行任何操作,这个应用就像静...
    Claire_wu阅读 1,939评论 3 30
  •   在多线程环境中,多个线程之间互相协作,以达到高效实现程序功能的目的,比如某些多线程程序要求线程执行有先后顺序、...
    小胡_鸭阅读 509评论 0 1

友情链接更多精彩内容