Skip to content

Instantly share code, notes, and snippets.

@misbell
Created October 5, 2016 18:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save misbell/2dc38c47ff56f91c6775dde2be1fceb4 to your computer and use it in GitHub Desktop.
Save misbell/2dc38c47ff56f91c6775dde2be1fceb4 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link
Author

misbell commented Oct 5, 2016

excellent, thank you!

@misbell
Copy link
Author

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