iOS多线程(二)--pthread

pthread

pthread是一套纯用C语言的API,需要程序员自己管理生命周期,基本很少使用。

导入头文件#import 

//在 C 语言中,没有对象的概念,对象是以结构体的方式来实现的
//通常,在 C 语言框架中,对象类型以 _t/Ref 结尾,而且声明时不需要使用 *
//创建线程对象
 pthread_t pthread =NULL;

举例:用pthread创建线程

//这里创建新线程(函数好长。。)
//第一个参数pthread_t *restrict:线程实体
//第二个参数const pthread_attr_t *restrict: 线程的属性
//第三个参数void *(*)(void *):void * 万能指针 与OC中的id类似 前面的void为返回值类型 ,函数名,后面的void*为参数类型
//第四个参数void *restrict:实际参数
pthread_create(<#pthread_t *restrict#>, <#const pthread_attr_t *restrict#>, <#void *(*)(void *)#>, <#void *restrict#>)
//新线程执行的任务
     void *thread(void *param) {
         return param;
     }

示例代码

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *string = @"PJABthread";
    //声明一个线程
    pthread_t thread;
    //创建一个新线程
    // 在混合开发时,如果在 C 和 OC 之间传递数据,需要使用 __bridge 进行桥接,桥接的目的就是为了告诉编译器如何管理内存
    int result = pthread_create(&thread, NULL, newThread, (__bridge void*)string);
    //返回值 0 创建线程成功,非0 创建失败
    NSLog(@"result = %d",result);
    NSLog(@"currentThread1 %@",[NSThread currentThread]);
}

void *newThread(void *pram){
    NSString *string = (__bridge NSString*)(pram);
    NSLog(@"pram = %@",pram);
    NSLog(@"string = %@",string);
    //新线程的线程位置和名称
    NSLog(@"currentThread2 %@",[NSThread currentThread]);
    return NULL;
}

运行结果

the result

你可能感兴趣的:(iOS多线程(二)--pthread)