美文网首页
pthread和NSthread的记录

pthread和NSthread的记录

作者: 什么的黑夜 | 来源:发表于2016-12-06 15:26 被阅读12次
  • pthread:
      //创建线程
       pthread_t pthread;
       pthread_create(&pthread, NULL, run, NULL);
    
      void *run(){
        NSLog(@"在子线程中执行!!!!");
        for (int i =1; i < 10; i++) {
            NSLog(@"%d",i);
            sleep(1);
            if (i == 5) {
                //取消线程操作:
                pthread_cancel(pthread);
            }
        }
        return NULL;
      }
    
  • NSThread
    一共有四种创建方式:
    1.alloc方式创建:
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
    thread.name =@"threadName";//可以设置线程的name,用以区分线程
    thread.threadPriority = 0.6;//设置线程的优先级,优先级越高执行的概率越高
    [self.thread start];//用以启动线程,否则不执行,对应的有一个静态方法:[NSThread exit]退出线程
    

2.detachNewThreadSelector方式创建:

  [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];

3.performSelectorInBackground方式创建:

 //有两种方式
 //创建子线程:
 [self performSelectorInBackground:@selector(run) withObject:nil];
 //回到主线程:
 [self performSelectorOnMainThread:@selector(backMainThread) withObject:nil waitUntilDone:YES];
  • 线程锁
    作用:保证代码能够完整执行,其他线程只能在锁外等待,直到解锁才能执行
    1. NSLock
    NSLock *lock = [[NSLock alloc]init];
    [lock lock];
      //需要保护的代码
      ...
    [lock unlock];
    
    1. @synchronized
    @synchronized (self) {
      //需要保护的代码
      ...
    }
    

相关文章

  • pthread和NSthread的记录

    pthread: //创建线程 pthread_t pthread; pthread_create(&p...

  • 基础语法-多线程

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

  • 多线程

    1,方式: NSThread、NSOperation、GCD、pThread 2,对比: NSThread: 优点...

  • iOS多线程以及在项目中的使用

    pThread几乎不用,不用管 NSThread NSThread是对pThread的封装优点:1.实时性更高2....

  • 多线程之NSThread

    Pthread 使用pthread必须盗用头文件#import 可以使用[NSThread...

  • iOS 多线程

    iOS使用线程的方式 pthread NSThread GCD NSOperation NSThread线程的创建...

  • iOS多线程总结

    pthread 使用方法 pthread是C语言的多线程库,使用pthread需要首先添加头文件 NSThread...

  • iOS 多线程 总结

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

  • 多线程(2)——NSThread

    iOS中实现多线程的四种方案 pthread NSThread GCD NSOpreation Pthread:这...

  • IOS多线程的方式

    pthread的基本使用(需要包含头文件) 需要#import 3 NSThread (1)NSThread的基本...

网友评论

      本文标题:pthread和NSthread的记录

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