记录runtime之Method Swizzling的实现

2015-10-15  本文已影响85人  懒得起名的伊凡

事件处理:响应者链条

多线程总结下哈:

什么是进程?进程就是系统正在运行的一个程序。每个进程之间是独立的,每个进程都运行在其专用并受保护的内存空间内。
什么是线程?

多线程

iOS的主线程:

pthread

使用C,跨平台的

    //创建线程
    pthread_t thread;
    pthread_create(&thread, NULL, run, NULL);

void *run(void *param)
{
    NSLog(@"Current Thread : %@",[NSThread currentThread]);
    return NULL;
}

NSThread

直接操作线程对象

- (void)nsthread
{
    //创建 虽然这里是局部变量,但是要等到执行完之后才会销毁,可以通过将其子类化,查看dealloc来进行验证。
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(nsthreadRun:) object:nil];
    //启动
//    [thread setStackSize:100];
//start 就是将线程放到可调度线程池里,这样CPU就会处理
    [thread start];
    
    //创建并直接启动
    [NSThread detachNewThreadSelector:@selector(aa:) toTarget:self withObject:nil];
    
    //还有一种方式 线程之间的通信
    [self performSelectorInBackground:@selector(aa:) withObject:nil];
    
//    self performSelectorOnMainThread:<#(nonnull SEL)#> withObject:<#(nullable id)#> waitUntilDone:<#(BOOL)#> modes:<#(nullable NSArray<NSString *> *)#>
    
    //强制停止线程
    [NSThread exit];
    
    //这个是整个程序挂掉
    exit(0);
}

- (void)nsthreadRun:(id)sender
{
    /*!
     @brief do something
     */
    //如果还需要在跳转到主线程进行UI什么de
    [self performSelectorOnMainThread:@selector(mainRun:) withObject:nil waitUntilDone:YES];
}

GCD

可充分利用多核。C语言开发。

NSOperation

基于GCD来实现的

多线程的安全隐患

加锁:

    //加锁的方式  可用任何一个对象 如[[NSObject alloc]init]
    @synchronized (self) {
        
    }

或者

    //加锁的方式
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, NULL);
    
    pthread_mutex_lock(&lock);
    pthread_mutex_unlock(&lock);
    pthread_mutex_trylock(&lock);
    pthread_mutex_destroy(&lock);

还有

    //加锁
    NSLock *lock1 = [[NSLock alloc]init];
    [lock1 lock];
    [lock1 tryLock];
    [lock1 unlock];

GCD中也有

@property(nonatomic,strong)dispatch_semaphore_t lock;
//注意lock不能声明为局部变量
    _lock = dispatch_semaphore_create(1);
    
    dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
    dispatch_semaphore_signal(_lock);

原子核非原子属性

OC在定义属性时有nonatomicatomic两种选择

程序执行时间计算

CFTimeInterval time = CFAbsoluteTimeGetCurrent();

RunLoop

使用RunLoop来保住线程的命,又能让他一直做事情。

利用NSPort来实现线程之间的通信

NSPort;
NSMessagePort;
NSMachPort;

不太重要,知道就行。

上一篇 下一篇

猜你喜欢

热点阅读