目录
1. pthread的概念
pthread是POSIX线程的简称,是线程的POSIX标准。pthread是基于C语言的,它是一种可以跨平台的使用方法,但是由于其使用难度较大,并且生命周期需要程序员手动管理,因此很少或几乎不用。
2. iOS中的使用
2.1 导入头文件
#import <pthread.h>
注:Xcode7以前需要导入的头文件是:#import <pthread/pthread.h>
2.2 代码格式
// 第一个参数:指向线程标识符的指针
// 第二个参数:线程的属性
// 第三个参数:线程要执行的函数
// 第四个参数:线程要执行函数的参数
// 返回值:0表示成功 非0表示失败
pthread_create(pthread_t _Nullable *restrict _Nonnull, const pthread_attr_t *restrict _Nullable, void * _Nullable (* _Nonnull)(void * _Nullable), void *restrict _Nullable);
2.3 代码示例
由于pthread是基于C语言的,因此给函数传参数的时候,就不能再使用@" "传参,而应该使用" "。 而要将OC中的对象传递给C语言中的函数时,需要用__bridge对其进行“桥接”。
2.3.1 不带参数
#import "ViewController.h"
#import <pthread/pthread.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建线程ID
pthread_t pthread;
// nil表示空对象,NULL表示空地址
int result = pthread_create(&pthread, NULL, showPthread, NULL);
// 0表示成功
// 非0表示失败
if (result == 0) {
NSLog(@"成功");
}
else{
NSLog(@"失败");
}
}
void *showPthread(){
NSLog(@"showPthread %@",[NSThread currentThread]);
return NULL;
}
@end
2.3.2 带参(C语言)
- (void)viewDidLoad {
[super viewDidLoad];
// 创建线程ID
pthread_t pthread;
// nil表示空对象,NULL表示空地址
int result = pthread_create(&pthread, NULL, showPthread, "viewDidLoad");
// 0表示成功
// 非0表示失败
if (result == 0) {
NSLog(@"成功");
}
else{
NSLog(@"失败");
}
}
void *showPthread(void *param){
NSLog(@"%s",param);
NSLog(@"showPthread %@",[NSThread currentThread]);
return NULL;
}
2.3.3 带参(OC语言)
- (void)viewDidLoad {
[super viewDidLoad];
// 创建线程ID
pthread_t pthread;
NSString *name = @"viewDidload";
// nil表示空对象,NULL表示空地址
int result = pthread_create(&pthread, NULL, showPthread, (__bridge void *)(name));
// 0表示成功
// 非0表示失败
if (result == 0) {
NSLog(@"成功");
}
else{
NSLog(@"失败");
}
}
void *showPthread(void *param){
NSString *name = (__bridge NSString *)(param);
NSLog(@"%@",name);
NSLog(@"showPthread %@",[NSThread currentThread]);
return NULL;
}