标签:
介绍NSThread之前先介绍一下pthread,仅供了解,一般在开发中用不到的
/*
参数说明:
1. pthread_t *restrict 线程代号的地址
2. const pthread_attr_t *restrict 线程的属性
3. 调用函数的指针
- void *(*)(void *)
- 返回值 (函数指针)(参数)
- void * 和 OC 中的 id 是等价的
4. void *restrict 传递给该函数的参数
返回值:
如果是0,表示正确
如果是非0,表示错误码
*/
NSString *str = @"lnj";
pthread_t thid;
int res = pthread_create(&thid, NULL, &demo, (__bridge void *)(str));
if (res == 0) {
NSLog(@"OK");
} else {
NSLog(@"error %d", res);
}
创建线程的几种方式:
// 1.创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(demo:) object:@"lnj"];
// 设置线程名称
[thread setName:@"xmg"];
// 设置线程的优先级
// 优先级仅仅说明被CPU调用的可能性更大
[thread setThreadPriority:1.0];
// 2.启动线程
[thread start];
+ (NSThread *)mainThread; // 获得主线程
- (BOOL)isMainThread; // 是否为主线程
+ (BOOL)isMainThread; // 是否为主线程
获得当前线程
NSThread *current = [NSThread currentThread];
线程的名字
- (void)setName:(NSString *)n;
- (NSString *)name;
// 1.创建线程后自动启动线程
[NSThread detachNewThreadSelector:@selector(demo:) toTarget:self withObject:@"lnj"];
// 1.创建线程
// 注意: Swift中不能使用, 苹果认为这个方法不安全
// 隐式创建并启动线程
[self performSelectorInBackground:@selector(demo:) withObject:@"lnj"];
启动线程
- (void)start;
// 进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态
阻塞(暂停)线程
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// 进入阻塞状态
//例:
// 睡眠5秒钟
[NSThread sleepForTimeInterval:5];
// 从当前时间睡3秒
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]];
强制停止线程
+ (void)exit;
// 进入死亡状态
注意:一旦线程停止(死亡)了,就不能再次开启任务
多线程的安全隐患
互斥锁使用格式:
@synchronized(锁对象)
{
// 需要锁定的代码
}
// 解锁
互斥锁的优缺点
互斥锁注意点
线程间的通信
原子和非原子属性
自旋锁 & 互斥锁
标签:
原文地址:http://www.cnblogs.com/wxdonly/p/5097271.html