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

来源:互联网 发布:pcb线路板软件下载 编辑:程序博客网 时间:2024/06/03 22:47
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事件。




0 0