前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS开发者多线程学习之旅

iOS开发者多线程学习之旅

作者头像
CC老师
发布2019-01-23 17:14:37
4290
发布2019-01-23 17:14:37
举报

多线程经典问题:资源共享

代码实现:

  • 形成一条资源的bug
  • 解决方案
  • 互斥锁小结
    • 保证锁内的代码,同一时间,只有一条线程能够执行!
    • 互斥锁的锁定范围,应该尽量小,锁定范围越大,效率越差!
  • 互斥锁参数
    • 能够加锁的任意 NSObject 对象
    • 注意:锁对象一定要保证所有的线程都能够访问
    • 如果代码中只有一个地方需要加锁,大多都使用 self,这样可以避免单独再创建一个锁对象

说到锁,我们再来看看苹果爸爸的给出干货Synchronization Costs and Performance

Synchronization

The presence of multiple threads in an application opens up potential issues regarding safe access to resources from multiple threads of execution. Two threads modifying the same resource might interfere with each other in unintended ways. For example, one thread might overwrite another’s changes or put the application into an unknown and potentially invalid state. If you are lucky, the corrupted resource might cause obvious performance problems or crashes that are relatively easy to track down and fix. If you are unlucky, however, the corruption may cause subtle errors that do not manifest themselves until much later, or the errors might require a significant overhaul of your underlying coding assumptions.

When it comes to thread safety, a good design is the best protection you have. Avoiding shared resources and minimizing the interactions between your threads makes it less likely for those threads to interfere with each other. A completely interference-free design is not always possible, however. In cases where your threads must interact, you need to use synchronization tools to ensure that when they interact, they do so safely.

OS X and iOS provide numerous synchronization tools for you to use, ranging from tools that provide mutually exclusive access to those that sequence events correctly in your application. The following sections describe these tools and how you use them in your code to affect safe access to your program’s resources.

atomic与nonatomic 的区别

  • nonatomic 非原子属性
  • atomic 原子属性(线程安全),针对多线程设计的,默认值
    • 保证同一时间只有一个线程能够写入(但是同一个时间多个线程都可以取值)
    • atomic 本身就有一把锁(自旋锁)
    • 单写多读:单个线程写入,多个线程可以读取
  • atomic:线程安全,需要消耗大量的资源
  • nonatomic:非线程安全,适合内存小的移动设备

iOS 开发的建议

  • 所有属性都声明为 nonatomic
  • 尽量避免多线程抢夺同一块资源
  • 尽量将加锁、资源抢夺的业务逻辑交给服务器端处理,减小移动客户端的压力

这是多线程系列的第三篇文章,下篇会继续探究多线程, 敬请期待...

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-08-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 HelloCode开发者学习平台 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档