Instantly share code, notes, and snippets.

Embed
What would you like to do?
os_unfair_lock, simple useage from wwdc 2016 concurrency talk by Pierre Habouzit, objective-c, bridging header and Swift 3
#import "FoundationLocks.h"
#import "os/lock.h"
@implementation LockableObject
os_unfair_lock _lock;
- (instancetype) init {
(os_unfair_lock){0};
return self;
}
- (void) lock {
os_unfair_lock_lock(&_lock);
}
- (void) unlock {
os_unfair_lock_unlock(&_lock);
}
// and header
#import <Foundation/Foundation.h>
@interface LockableObject : NSObject
- (void) lock;
- (void) unlock;
@end
// and bridging header
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "FoundationLocks.h"
// and Swift
let l = LockableObject()
let _ = l.lock()
let _ = l.unlock()
@MadCoder

This comment has been minimized.

MadCoder commented Oct 5, 2016

@implementation LockableObject {
    os_unfair_lock _lock;
}

- (instancetype) init
{
    if ((self = [super init])) {
        self->_lock = OS_UNFAIR_LOCK_INIT;
    }
    return self;
}
@end
@misbell

This comment has been minimized.

Owner

misbell commented Oct 5, 2016

excellent, thank you!

@misbell

This comment has been minimized.

Owner

misbell commented Oct 5, 2016

here's the trylock

  • (Boolean) trylock {

    if (os_unfair_lock_trylock(&_lock)) {
    return true;
    }
    return false;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment