码迷,mamicode.com
首页 > 编程语言 > 详细

多线程小结

时间:2015-07-31 12:16:08      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:

  进程可以理解为运行在系统的应用程序,进程之间是独立的,一个进程可以创建多个线程,提高工作效率,但会增加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;

 

多线程小结

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!