pthread使用(多线程002)

来源:互联网 发布:php cms 免费无需授权 编辑:程序博客网 时间:2024/05/11 03:29

由于pthread主要是c语言接口, 对于不同平台可移植性比较好, 对于大公司来说使用较多, 但是线程生命周期需要程序猿自己管理,所以对于可移植性要求不高的地方几乎很少有人使用, 这里只做一些简单的介绍和示例.  

1. 导入头文件

#import <pthread.h>

2. 使用创建函数

int pthread_create(pthread_t * __restrict, const pthread_attr_t * __restrict,        void *(*)(void *), void * __restrict);

3. 参数解释

 pthread_t:线程的编号,地址 pthread_attr_t:线程的属性 void *(*)(void *):指定该线程要运行的方法(函数指针) void *:运行指定函数的参数

void * 指向任意类型的指针

函数指针前加上*号或&号或直接写函数名字都表示函数的首地址

4.返回值

0 :创建线程成功非0:创建线程失败

5.Example

int result = pthread_create(&pid, NULL, &demo, (__bridge void *)str);    if (result == 0) {        //        NSLog(@"成功");    }else{        NSLog(@"失败");    }void * demo(void *param){    NSString *str = (__bridge NSString *)(param);    NSLog(@"%@",str);//    for (int i = 0; i < 10000; i++) {//        NSLog(@"abc %@",[NSThread currentThread]);//    }    return NULL;}
0 0
原创粉丝点击