iOS开发之多线程的实现(pthread)

 

目录

1. pthread的概念

2. iOS中的使用

2.1 导入头文件

2.2 代码格式

2.3 代码示例

2.3.1 不带参数

2.3.2 带参(C语言)

2.3.3 带参(OC语言)


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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值