ios
来源:互联网 发布:死性不改网络歌手歌词 编辑:程序博客网 时间:2024/06/05 10:08
在很多操作系统上都会用到的API,可移植性特别强。基于C语言框架,在开发过程中极少用到。在很多面试中对该线程使用都很少提及。
那么好,我们言归正传,以代码的形式给大家讲解用法和注意事项。
——————
思路:
在界面上安排一个按钮,当点击按钮时,执行 pThread 多线程;
代码演示:
1:创建项目;
2:在ViewController里面添加按钮,代码如下:
//第一种方式 pThreadUIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];btn.frame = CGRectMake(40, 100, 100, 40);[btn setTitle:@"pThread" forState:UIControlStateNormal];[btn setBackgroundColor:[UIColor blueColor]];[btn addTarget:self action:@selector(click_pThread) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:btn];
3:实现 click_pThread 事件
- (void)click_pThread { // [self isMainThread]; NSLog(@"我在主线程中执行"); pthread_t queue; // pthread_create : 创建任务的方法,/* 第一个参数:pthread指针 第二个参数:可为空; 第三个参数:要在子线程中执行的代码 第四个参数:可为空; */pthread_create(&queue, NULL, run_pThread, NULL);}
4:定义 run_pThread 方法
// C 语言 函数定义方式void *run_pThread(void *data) { NSLog(@"我在子线程中执行"); //一个模拟任务的执行 for (int i = 0; i < 10 ; i ++) { sleep(1); NSLog(@"%d",i); } return NULL;}
5:运行,观察控制台
0 0