[网络和多线程]2、pThread 的基本使用方法(不推荐使用)

本文介绍如何在iOS开发中利用pThread库实现线程并发操作,通过实例展示了如何创建并管理子线程,以及如何在主线程与子线程间进行资源的共享与同步,同时保持UI流畅性。
2、pThread 的基本使用方法(不推荐使用)
    【网络多线程】
--------------------------------------------------------------------------------------------------------------

//

//  ViewController.m

//  hello

//

//  Created by zhaoli on 15/9/30.

//  Copyright © 2015 hello. All rights reserved.

//


#import "ViewController.h"

#import <pthread.h>


@interface ViewController ()

- (IBAction)btnClick;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


/**

 *  子线程的任务,执行耗时的操作

 */

void *run(void *data)

{

    NSThread *curThread = [NSThread currentThread];


    // 耗时操作

    for (int i = 0; i < 5000 ; i++) {

        NSLog(@"run --- %@",curThread);

    }

    

    return NULL;

}


- (IBAction)btnClick {

    // 1、获得当前的线程,打印线程

    NSThread *curThread = [NSThread currentThread];

    NSLog(@"run --- %@",curThread);

    

    // 2、创建一条子线程,执行一些耗时的操作

    pthread_t threadID;

    /**

     *  创建子线程

     *

     *  @param pthread *restrict : 线程的ID,线程创建成功后返回一个ID

     *  @param const pthread_attr_t *restrict : 线程的一些属性

     *  @param void * (*)(void *) : 形参和返回值都是void *类型的函数指针,线程

                开启后要执行的任务

     *   @param void *restrict 

     *

     *  @return <#return value description#>

     */

    pthread_create(&threadID, NULLrun , NULL);


}


执行结果:


可以看出run的执行处于子线程,而 按钮的点击事件的处理是处于 主线程,虽然子线程
run在打印输出信息,他执行过程是非常耗时的,但是主线程并没有阻塞,在打印输出的同时可
以流畅的处理其他的UI事件。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值