UI笔记

多线程介绍

2015-04-16  本文已影响264人  冷漠叻荭颜

进程\线程


多线程


同步和异步

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    // 异步执行
    [self performSelectorInBackground:@selector(test) withObject:nil];
    NSLog(@"over");
}

// 演示耗时操作
- (void)test {
    for (int i = 0; i < 1000 ; i++) {
        // 操作栈空间 速度特别快
        // int n = 10;
        // 操作堆空间,速度慢
        // NSString *str = [NSString stringWithFormat:@"abc %d",i];
        // io操作  input output
        NSLog(@"abc");
    }
}

iOS中多线程的实现方案

int pthread_create(pthread_t * __restrict,
    const pthread_attr_t * __restrict,
    void *(*)(void *),
    void * __restrict);
// 参数:
// 第1个参数为指向线程标示符的指针(线程编号的地址)
// 第2个参数用来设置线程属性
// void *(*)(void *) 返回值 (函数指针)(参数)
// void * 返回值类型,类似于OC中的id
// (*) 函数的指针
// (void *) 参数列表
// 第3个参数是线程调用函数指针
// 第4个参数是运行函数的参数

// 返回值:
// 返回0 线程创建成功 此时第1个参数是新线程的编号
// 非0 线程创建失败 返回对应错误码
pthread的使用
// 通过NSThread开启1个子线程的3种方式
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg;
NSThread的使用 线程的状态 线程的属性

多线程访问共享资源的问题

线程执行到@synchronized
① 检查锁的状态 如果是开锁状态(1)转到② 如果上锁(0)转到⑤
② 上锁(0)
③ 执行代码块
④ 执行完毕 开锁(1)
⑤ 线程等待(就绪状态)

未使用互斥锁 多线程同时访问共享资源引起的问题
使用互斥锁解决多线程访问共享资源的问题
上一篇下一篇

猜你喜欢

热点阅读