美文网首页
多线程(Pthread/NSThread)

多线程(Pthread/NSThread)

作者: JS_swh | 来源:发表于2017-03-20 10:36 被阅读0次

Pthread简单使用

// 1. 创建线程对象
pthread_t thread;    
// 2. 创建线程
/*
   1>第一个参数
     线程对象地址
   2>第二个参数
     线程属性 不需要传NULL
   3>第三个参数
     指向函数的指针
   4>函数需要接受的参数
     函数需要传递的参数
*/
pthread_create(&thread, NULL, task, NULL);

// 判断两条线程是否相等
pthread_equal(threadA, threadB);

void *task(void *param)
{
   return NULL;
}

NSThread基本使用

//线程生命周期: 任务执行完毕后释放线程
// 创建线程(第一种)
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(text:) object:@""];
// 线程优先级(0~1)默认0.5 只是提高调用概率 不是100%调用
thread.threadPriority
// 启动线程
[thread start];

// 创建线程(第二种)
[NSThread detachNewThreadSelector:@selector(text:) toTarget:self withObject:@""];

// 创建线程(第三种)
[self performSelectorInBackground:@selector(text:) withObject:@""];

线程的状态

// 创建线程后 处于新建线程状态
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(text:) object:@""];
// 开启线程  线程会进入"可调度线程池里"等待执行 就绪<--->运行
[thread start];
// 线程的阻塞状态
[NSThread sleepUntilDate:<#(nonnull NSDate *)#>];
[NSThread sleepForTimeInterval:<#(NSTimeInterval)#>];
// 强制停止线程 线程死亡
[NSThread exit];

线程的安全

// 多个线程同时访问一块资源 会引发数据错乱或数据安全问题 (存取钱问题)
// 1. 互斥锁 (会消耗大量CPU)
@synchronized (self) {
    // 执行代码
}
// 原子属性(atomic) 非原子属性(nonatomic)
// atomic:会对属性setter方法自动加锁

线程间通讯

// 一个线程任务执行完成后 转到另一个线程执行其他任务
// 回主线程执行方法
[self performSelectorOnMainThread:<#(nonnull SEL)#> withObject:<#(nullable id)#> waitUntilDone:<#(BOOL)#>]
// 到其他线程执行方法
[self performSelector:<#(nonnull SEL)#> onThread:<#(nonnull NSThread *)#> withObject:<#(nullable id)#> waitUntilDone:<#(BOOL)#>];

相关文章

  • 基础语法-多线程

    多线程的实现方案:pthread / NSThread / GCD / NSOperation pthread 基...

  • OC_NSThread

    原文链接:iOS多线程--彻底学会多线程之『pthread、NSThread』 **NSThread **是苹果官...

  • OC多线程分享pthread&NSThread

    一.多线程基础{ 二.pthread{ 三.NSThread{

  • iOS多线程 NSOperation

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程 pthread、NSThread

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程: GCD

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程运用

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS多线程基础

    系列文章: 多线程 多线程 pthread、NSThread 多线程 GCD 多线程 NSOperation 多线...

  • iOS 多线程 总结

    多线程技术方案 pthread NSThread GCD NSOperation 1.pthread 特点 程序员...

  • 重点复习

    多线程:pthread,NSThread,GCD,NSOperation&NSOperationQueue。 de...

网友评论

      本文标题:多线程(Pthread/NSThread)

      本文链接:https://www.haomeiwen.com/subject/kdybnttx.html