#import "ViewController.h"
#import <pthread.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// pthread
// void *: C语言中的void * == OC中的id
// 查看当前方法的执行线程 [NSThread currretnThread]
// 一般 C语言的数据类型,以 _t 结尾.
// Foundation OC
// Core Foundation C
NSString *str = @"123";
CFStringRef str1 = (__bridge CFStringRef)(str);
NSArray *array = nil;
CFArrayRef arr = (__bridge CFArrayRef)(array);
NSDictionary *dict = nil;
CFRelease(str1);
// 不要为nil 不然会程序会挂掉
// CFRelease(arr);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touchesBegan:%@",[NSThread currentThread]);
pthread_t myThread;
// 参数
// OC 数据类型不能直接传递给c语言的函数.
//
// 混合开发的时候,有哪些注意点:内存问题?C语言没有自动内存管理.
// OC: ARC: OC不许要手动内存管理(内存管理操作 :retain/release/autorelease)
// OC: MRC: 需要手动进行内存管理
// C 语言:无论是ARC还是MRC,都需要手动进行内存管理.
// ARC:
// 通过 桥接 告诉编译器 是否添加自动内存管理操作
// MRC下不需要桥接.
// 解释性语言: xml html(通过标签直接解释,不需要编译)
// 编译性语言: OC java
NSString *str = @"hello pthread";
// 创建线程
int result = pthread_create(&myThread, NULL, run, (__bridge void *)(str));
NSLog(@"%d",result);
}
// 线程中执行的函数
// void *data :接收一个任意类型的参数
void *run (void *data)
{
NSString *str = (__bridge NSString *)(data);
for (int i = 0; i < 100; ++i) {
NSLog(@"--------%d,%@,%@",i,str,[NSThread currentThread]);
}
return NULL;
}
- (void)pthreadTest
{
// 查看当前方法的执行线程 [NSThread currretnThread]
NSLog(@"touchesBegan:%@",[NSThread currentThread]);
//{number = 1, name = main}
// number = 1 : 就标识是主线程 只要number = 1 就是主线程.
// number = 2, name = (null)
// 只要 number != 1,就表示子线程
// 用pthread开启线程
// pthread_t :标识一条线程
pthread_t myThread;
// 参数
// ;:取线程标识符的地址
// <#const pthread_attr_t *restrict#>:设置线程的属性.
// <#void *(*)(void *)#>:函数(开启的线程中执行的函数)
// void *: C语言中的void * == OC中的id
// <#void *restrict#>:传递给执行函数的参数
// 返回值
// 对执行函数来说,如果返回值为0 一般代表创建/执行成功.
// 如果执行失败,会返回一些失败的错误码.
// 创建线程
int result = pthread_create(&myThread, NULL, run, NULL);
NSLog(@"%d",result);
}