iOS 进阶-高阶_多线程_Pthread

作者: SunnyLeong | 来源:发表于2018-03-06 08:38 被阅读80次

C语言的库 : user/include

POSIX线程(POSIX threads),简称Pthreads,是线程的POSIX标准。该标准定义了创建和操纵线程的一整套API。在类Unix操作系统(Unix、Linux、Mac OS X等)中,都使用Pthreads作为操作系统的线程。

这是一套在很多操作系统上都通用的多线程API,所以移植性很强,当然在 iOS 中也是可以的。不过这是基于 c语言 的框架,感受一下:

//第一步要包含头文件
#import <pthread.h>

//创建pthread方法解析
int pthread_create(
        pthread_t _Nullable * _Nonnull __restrict, //1.指向线程代号的指针
        const pthread_attr_t * _Nullable __restrict, //2.线程的属性
        void * _Nullable (* _Nonnull)(void * _Nullable), //3.指向函数的指针
        void * _Nullable __restrict // 4.传递给该函数的参数
                            );
  /**
  int 返回值 
     - 如果是0,标示正确
     - 如果非0,标示错误代码

   Nullable 不能为空

   参数3详解:
     void *   (*)      (void *)
     返回值   (函数指针)  (参数)
     void *  和OC中的  id 是等价的!

    __bridge :
     - 在 ARC 开发中,如果涉及到和C语言中的相同的数据类型进行转换,需要使用 __bridge "桥接"
     - 在 MRC 不需要

  */


//button点击事件
- (void)clickForButton{
    
    NSString * str = @"hello";
    pthread_t threadId;
    
    int result = pthread_create(&threadId, NULL, &demo, (__bridge  void *)(str));
    
    if (result == 0) {
        NSLog(@"success");
    }else{
        NSLog(@"error %d",result);
    }
}

//C函数
void * demo(void * param){

      NSLog(@"%@ %@",[NSThread currentThread],param);

            //[NSThread currentThread] 判断是否是在主线程
            // number == 1 说明是主线程  != 1 就是其他线程
    return NULL;
}

看代码就会发现他需要 c语言函数(demo方法),还需要手动处理线程的各个状态的转换即管理生命周期,比如,这段代码虽然创建了一个线程,但并没有销毁。


下一节 : NSThread

相关文章

网友评论

    本文标题:iOS 进阶-高阶_多线程_Pthread

    本文链接:https://www.haomeiwen.com/subject/qkyhfftx.html