ios 多线程

  一、多线程的优缺点

  二、主线程:

  三、多线程的技术方案

  四、线程状态和属性

  五、多线程访问共享资源的问题

一、多线程的优缺点:

     优点:

       1.能适当提高程序的执行效率

       2.能适当提高资源的利用率(cpu,内存); 

       3.线程上的任务执行完成之后,线程会自动销毁;

     缺点: 

      1.开启线程需要占用一定的内存空间(默认占用512KB);

      2.开启大量的线程,会占用大量的内存空间,降低程序的性能;

      3.线程越多,cpu在调用线程上的开销就越大;

      4.程序设计更加复杂,比如线程间的通信,多线程的数据共享

二、主线程:

           一个程序运行后,默认会开启一个线程,称为主线程或 ui线程,主线程一般用来刷新ui界面,处理ui事件(点击、滚动、拖拽)

          使用注意:

               1.不要将耗时操作放到主线程中

              2.耗时操作会卡住主线程,严重影响ui的流畅度,给用户一种卡的体验;   

三、多线程的技术方案

            1、pthread

  /**
     参数一:线程编号的地址
     参数二:线程的属性
     参数三:线程要执行的函数  void *   (*)   (void *)
             //int *指向int类型的指针   void *指向任何类型的指针  类似oc中的id
     参数四:要执行的函数的参数
     
     函数的返回值 :int  0是成功   非0是失败
     */
    pthread_t pthread;//线程编号
//    char *name="zs";
    NSString *name=@"zs";
    //把oc中的对象传递给C语言的函数要桥接,反过来也一样
    int result= pthread_create(&pthread, NULL , demo, (__bridge void *)(name));
    if(result==0){
         NSLog(@"成功");
    }else{
         NSLog(@"失败");
    }

void *demo(void *param){
    //param:name的值,传的参数
    NSString *name=(__bridge NSString *)(param);
    NSLog(@"执行 %@ %@",name,[NSThread currentThread]);
    return NULL;
}

           2、NSThread

               

 /**
        方式一
     */
    NSThread *thread=[[NSThread alloc] initWithTarget:self selector:@selector(threadDemo) object:nil];
    [thread start];
    /**
        方式二
    */
    [NSThread detachNewThreadSelector:@selector(threadDemo) toTarget:self withObject:nil];
    
    /**
        方式三
    */
    [self performSelectorInBackground:@selector(threadDemo) withObject:nil];
    
    /**
       带参数
    */
    NSThread *threadParameter=[[NSThread alloc] initWithTarget:self selector:@selector(threadDemoParameter:) object:@"我是参数的值"];
       [threadParameter start];

            

- (void) threadDemo{
     NSLog(@"threadDemo执行 %@",[NSThread currentThread]);
}
- (void) threadDemoParameter:(NSString *)name{
     NSLog(@"threadDemo执行 %@",[NSThread currentThread]);
     NSLog(@"threadDemo执行 %@ 
 %@",[NSThread currentThread],name);
}

   

  四、线程状态和属性

           

    [NSThread sleepForTimeInterval:3];//线程休眠3秒
    [NSThread exit];//线程退出

      [NSThreadisMainThread];//判断当前线程是否是主线程

      threadParameter.threadPriority=1.0;//设置线程的优先级,0-1 数字越大优先级越高;

        五、多线程访问共享资源的问题

              当多线程访问同一块资源时,很容易引发数据错乱和数据安全问题

              解决方法:加上线程锁    互斥锁 :实现线程同步      加锁会影响程序的性能

             

 @synchronized (self) {
        //要加锁的逻辑
    }

           

           

原文地址:https://www.cnblogs.com/huihuizhang/p/12916787.html