【原创】http://www.cnblogs.com/luoguoqiang1985

今天遇见了这问题,决定要需要讨论下。

线程同步的方法:

  • @synchronized

官方文档解释:The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code.

个人理解:@synchronized关键字提供了互锁功能。

示例代码:

static NSObject *lockObj = nil;

if (lockObj == nil) {
lockObj = [[NSObject alloc] init];
}
dispatch_async(dispatch_get_global_queue(, ), ^{
NSLog(@"A thread try lock!");
@synchronized(lockObj) {
NSLog(@"A thread lock, please wait!");
[NSThread sleepForTimeInterval:];
NSLog(@"A thread unlock!");
} });
dispatch_async(dispatch_get_global_queue(, ), ^{
NSLog(@"B thread try lock!");
@synchronized(lockObj) {
NSLog(@"B thread lock, please wait!");
[NSThread sleepForTimeInterval:];
NSLog(@"B thread unlock!");
} });

执行结果:

2013-12-28 21:11:02.332 Objc[1341:1b03] A thread try lock!
  2013-12-28 21:11:02.335 Objc[1341:1b03] A thread lock, please wait!
  2013-12-28 21:11:02.332 Objc[1341:3907] B thread try lock!
  2013-12-28 21:11:12.336 Objc[1341:1b03] A thread unlock!
  2013-12-28 21:11:12.336 Objc[1341:3907] B thread lock, please wait!
  2013-12-28 21:11:17.337 Objc[1341:3907] B thread unlock!

实验结果已经证明同步效果不错!

  • NSLock

官方解释:An NSLock object is used to coordinate the operation of multiple threads of execution within the same application. An NSLock object can be used to mediate access to an application’s global data or to protect a critical section of code, allowing it to run atomically.

个人理解:在一个应用里面协调线程间的执行。

  示例代码:

昨晚键盘突然坏了,郁闷啊,早上赶紧入货。继续写博了。

static NSLock *lockMain = nil;

if (lockMain == nil) {
lockMain = [[NSLock alloc] init];
} dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [lockMain lock];
        NSLog(@"A thread begin +!");
        [NSThread sleepForTimeInterval:10];
        NSLog(@"A thread + done and unlock!");
        [lockMain unlock];
        [lockMain lock];
        NSLog(@"A thread begin -!");
        [NSThread sleepForTimeInterval:10];
        NSLog(@"A thread - done and unlock!");
        [lockMain unlock];
    });
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [lockMain lock];
        NSLog(@"B thread begin *!");
        [NSThread sleepForTimeInterval:10];
        NSLog(@"B thread * done and unlock!");
        [lockMain unlock];
        [lockMain lock];
        NSLog(@"B thread begin /!");
        [NSThread sleepForTimeInterval:10];
        NSLog(@"B thread / done and unlock!");
        [lockMain unlock];
    });

  执行结果:

2013-12-29 14:37:44.808 Objc[1219:1303] A thread begin +!
2013-12-29 14:37:54.811 Objc[1219:1303] A thread + done and unlock!
2013-12-29 14:37:54.812 Objc[1219:1d03] B thread begin *!
2013-12-29 14:38:04.813 Objc[1219:1d03] B thread * done and unlock!
2013-12-29 14:38:04.813 Objc[1219:1303] A thread begin -!
2013-12-29 14:38:14.815 Objc[1219:1303] A thread - done and unlock!
2013-12-29 14:38:14.816 Objc[1219:1d03] B thread begin /!
2013-12-29 14:38:24.817 Objc[1219:1d03] B thread / done and unlock!

  • NSConditionLock

官方解释:

  The NSConditionLock class defines objects whose locks can be associated with specific, user-defined conditions. Using an NSConditionLock object, you can ensure that a thread can acquire a lock only if a certain condition is met. Once it has acquired the lock and executed the critical section of code, the thread can relinquish the lock and set the associated condition to something new. The conditions themselves are arbitrary: you define them as needed for your application.

个人理解:

根据条件加锁与解锁。

示例代码:

static NSConditionLock *cdtLock = nil;
#define A_THREAD 1
#define B_THREAD 2
#define C_THREAD 3 __block NSInteger a = B_THREAD;
if (cdtLock == nil) {
cdtLock = [[NSConditionLock alloc] initWithCondition:a];
} dispatch_async(dispatch_get_global_queue(, ), ^{
NSLog(@"A thread run!");
BOOL canLock = [cdtLock tryLockWhenCondition:A_THREAD];
if (!canLock) {
NSLog(@"A Thread Lock fail,exit!");
return ;
}
NSLog(@"A thread begin lock!");
[NSThread sleepForTimeInterval:];
NSLog(@"A thread unlock!");
[cdtLock unlock];
}); dispatch_async(dispatch_get_global_queue(, ), ^{
NSLog(@"B thread run!");
BOOL canLock = [cdtLock tryLockWhenCondition:B_THREAD];
if (!canLock) {
NSLog(@"B Thread Lock fail,exit!");
return ;
}
NSLog(@"B thread begin lock!");
[NSThread sleepForTimeInterval:];
NSLog(@"B thread unlock!");
[cdtLock unlock];
}); dispatch_async(dispatch_get_global_queue(, ), ^{
NSLog(@"C thread run!");
BOOL canLock = [cdtLock tryLockWhenCondition:C_THREAD];
if (!canLock) {
NSLog(@"C Thread Lock fail,exit!");
return ;
}
NSLog(@"C thread begin lock!");
[NSThread sleepForTimeInterval:];
NSLog(@"C thread unlock!");
[cdtLock unlock];
});

执行结果:

2013-12-29 20:46:27.426 Objc[6282:1303] A thread run!
   2013-12-29 20:46:27.466 Objc[6282:1303] A Thread Lock fail,exit!
  2013-12-29 20:46:27.426 Objc[6282:1e03] C thread run!
  2013-12-29 20:46:27.468 Objc[6282:1e03] C Thread Lock fail,exit!
  2013-12-29 20:46:27.426 Objc[6282:1c03] B thread run!
  2013-12-29 20:46:27.481 Objc[6282:1c03] B thread begin lock!

  • NSRecursiveLock 递归锁

  官方文档:

NSRecursiveLock defines a lock that may be acquired multiple times by the same thread without causing a deadlock, a situation where a thread is permanently blocked waiting for itself to relinquish a lock. While the locking thread has one or more locks, all other threads are prevented from accessing the code protected by the lock.

个人理解:

同一个线程可以多次请求加锁,但不会引起死锁。

示例代码:

static NSRecursiveLock *lock;

 if (lock == nil) {
lock = [[NSRecursiveLock alloc] init];
}
void (^__block DoLog)(int) = ^(int value){
[lock lock];
if (value > ) {
DoLog(value-);
}
NSLog(@"value is %d", value);
[lock unlock];
};
dispatch_async(dispatch_get_global_queue(, ), ^{
NSLog(@"test begin");
DoLog();
NSLog(@"test end");
});

执行结果:

2013-12-29 21:15:31.567 Objc[6741:1303] test begin
2013-12-29 21:15:31.570 Objc[6741:1303] value is 0
2013-12-29 21:15:31.571 Objc[6741:1303] value is 1
2013-12-29 21:15:31.574 Objc[6741:1303] value is 2
2013-12-29 21:15:31.575 Objc[6741:1303] value is 3
2013-12-29 21:15:31.576 Objc[6741:1303] value is 4
2013-12-29 21:15:31.577 Objc[6741:1303] value is 5
2013-12-29 21:15:31.578 Objc[6741:1303] test end

block竟然也可以递归调用,神奇!

ios专题 -线程互斥与同步的更多相关文章

  1. C++线程互斥、同步

     一.线程互斥 如果多个线程需要访问且可能修改同一个变量,那么需要加锁,保证同一时刻只有一个线程可以访问,这个动作即最小“原子操作” 方式1: 使用c++提供的类mutex,lock,unlock即可 ...

  2. Linux高级编程--09.线程互斥与同步

    多个线程同时访问共享数据时可能会冲突,比如两个线程都要把某个全局变量增加1,这个操作在某平台需要三条指令完成: 从内存读变量值到寄存器 寄存器的值加1 将寄存器的值写回内存 假设两个线程在多处理器平台 ...

  3. 【原】iOS多线程之线程间通信和线程互斥

    线程间通信 1> 线程间通信分为两种 主线程进入子线程(前面的方法都可以) 子线程回到主线程 2> 返回主线程 3> 代码 这个案例的思路是:当我触摸屏幕时,会在子线程加载图片,然后 ...

  4. c++并发编程之线程的互斥与同步

    什么是线程的同步与互斥? 互斥:指在某一时刻指允许一个进程运行其中的程序片,具有排他性和唯一性. 对于线程A和线程B来讲,在同一时刻,只允许一个线程对临界资源进行操作,即当A进入临界区对资源操作时,B ...

  5. JAVA多线程提高二:传统线程的互斥与同步&传统线程通信机制

    本文主要是回顾线程之间互斥和同步,以及线程之间通信,在最开始没有juc并发包情况下,如何实现的,也就是我们传统的方式如何来实现的,回顾知识是为了后面的提高作准备. 一.线程的互斥 为什么会有线程的互斥 ...

  6. python多线程编程(3): 使用互斥锁同步线程

    问题的提出 上一节的例子中,每个线程互相独立,相互之间没有任何关系.现在假设这样一个例子:有一个全局的计数num,每个线程获取这个全局的计数,根据num进行一些处理,然后将num加1.很容易写出这样的 ...

  7. Python之多线程:线程互斥与线程同步

    一.锁在多线程中的使用:线程互斥 lock = threading.Lock()#创建一个锁对象 1.with lock: pass 和进程使用的方式相同   2.控制线程结束的时间 通过一个全局变量 ...

  8. 【Java并发专题之三】Java线程互斥、协作原理

    (I)Java线程互斥原理之synchronized原理 从JDK5引入CAS原子操作,但没有对synchronized关键字做优化,而是增加了J.U.C.concurrent,concurrent包 ...

  9. Linux 线程间的同步与互斥

    在线程并发执行的时候,我们需要保证临界资源的安全访问,防止线程争抢资源,造成数据二义性. 线程同步: 条件变量 为什么使用条件变量? 对临界资源的时序可控性,条件满足会通知其他等待操作临界资源的线程, ...

随机推荐

  1. 深入设计模式(二)——单例模式(Singleton Pattern)

    一.单例模式介绍 单例模式(Singleton Pattern),保证一个类只有一个实例,并提供一个访问它的全局访问点.单例模式因为Singleton封装它的唯一实例,它就可以严格地控制客户怎样访问它 ...

  2. js函数参数设置默认值

    php有个很方便的用法是在定义函数时可以直接给参数设默认值,如: function simue ($a=1,$b=2){  return $a+$b;}echo simue(); //输出3echo ...

  3. HashMap原理

    1. HashMap概述 HashMap是基于哈希表的Map接口的非同步实现.此实现提供所有可选的映射操作,并允许使用null值和null键.此类不保证映射的顺序,特别是它不保证该顺序恒久不变. 2. ...

  4. php连接mysql数据库练手

    <?php $servername = "localhost"; $username = "yosha"; $password = "leon0 ...

  5. storm spout的速度抑制问题

    转发请注明原文地址:http://www.cnblogs.com/dongxiao-yang/p/6031398.html 最近协助同事优化一个并发消费kafka数据用来计算的任务,压测过程中发现有两 ...

  6. Node调试工具JSHint

    Node调试工具JSHint的安装及配置教程 作者: 字体:[增加 减小] 类型:转载 时间:2014-05-27我要评论 Node的优势我就不再乱吹捧了,它让javascript统一web的前后台成 ...

  7. Android学习(一)

    #常见布局 ###线性布局 有一个布局方向,水平或者竖直 在竖直布局下,左对齐.右对齐,水平居中生效 在水平布局下,顶部对齐.底部对齐.竖直居中生效 权重:按比例分配屏幕的剩余宽度或者高度 ###相对 ...

  8. 【剑指Offer学习】【面试题40:数组中仅仅出现一次的数字】

    题目:一个整型数组里除了两个数字之外.其它的数字都出现了两次,请敲代码找出这两个仅仅出现一次的数字. 要求时间复杂度是O(n),空间复杂度是O(1). 举例说明 比如输入数组{2, 4, 3, 6, ...

  9. HTML5到底能给企业带来些什么?

    一.改变企业网络广告的模式与分布 广告是企业网络营销的主要方式之一.十几年来,无论是展示还是互动,基本被Adobe Flash所主宰.然而,HTML5网页的多媒体特性.三维.图形及特效,超炫的浏览体验 ...

  10. Activity中的四种启动模式

    在Android中每个界面都是一个Activity,切换界面操作其实是多个不同Activity之间的实例化操作.在Android中Activity的启动模式决定了Activity的启动运行方式. An ...