多线程小结

  进程可以理解为运行在系统的应用程序,进程之间是独立的,一个进程可以创建多个线程,提高工作效率,但会增加cpu的负荷。

1,线程的创建:

  方式1:比较少用

  pthread_t thread;

  pthread_create(&thread, NULL, run, NULL);

  方式2:

  NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"线程A"];

  [thread start]

  方式3:

  [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"创建完自动启动"];

  方式4:隐式创建线程, 并且自动启动

  [self performSelectorInBackground:@selector(run:) withObject:@"隐式创建"];

2,线程共享资源的处理:

  1,通过对代码加互斥锁,避免多线程访问数据紊乱

    @synchronized(self){

      //代码区

    }

  2,对属性设置为atomic,(一般设置为nonatomic);测试有点问题。

3,线程间的通信

  - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;

  - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;

原文地址:https://www.cnblogs.com/god-love-yao/p/4691399.html