double checked locking - objective c - objective-c

I realised double checked locking is flawed in java due to the memory model, but that is usually associated with the singleton pattern and optimizing the creation of the singleton.
What about under this case in objective-c:
I have a boolean flag to determine if my application is streaming data or not. I have 3 methods, startStreaming, stopStreaming, streamingDataReceived and i protect them from multiple threads using:
- (void) streamingDataReceived:(StreamingData *)streamingData {
if (self.isStreaming) {
#synchronized(self) {
if (self.isStreaming) {
- (void) stopStreaming {
if (self.isStreaming) {
#synchronized(self) {
if (self.isStreaming) {
- (void) startStreaming:(NSArray *)watchlistInstrumentData {
if (!self.isStreaming) {
#synchronized(self) {
if (!self.isStreaming) {
Is this double check uneccessary? Does the double check have similar problems in objective-c as in java? What are the alternatives to this pattern (anti-pattern).
Thanks

It is equally flawed - you have a race condition
You have to enter your synchronized section and then check the flag

That looks like premature optimisation to me. What's wrong with (for example)
- (void) startStreaming:(NSArray *)watchlistInstrumentData {
#synchronized(self) {
if (!self.isStreaming) {
...

Related

Disk Arbitration Objective C: Put All Drives and Partitions in an Array

I am just starting out in this wacky world of programming and I have come across a very frustrating problem:
I am trying to use Disk Arbitration Framework to put all Disks in a array.
#import "DiskDetector.h"
#import "Disk.h"
#implementation DiskDetector
-(id)init {
self.arrayOfDisks = [[NSMutableArray alloc]init];
DASessionRef session;
session = DASessionCreate(kCFAllocatorDefault);
DARegisterDiskAppearedCallback(session, kDADiskDescriptionMatchVolumeMountable,diskAppearedCallback,NULL);
DARegisterDiskDisappearedCallback(session,kDADiskDescriptionMatchVolumeMountable, diskDisappearedCallback, NULL);
DASessionScheduleWithRunLoop(session, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
return self;
}
-(void)addToArrayOfDisks:(Disk*)disk {
}
void diskAppearedCallback(DADiskRef disk, void* context)
{
Disk *theDisk = [[Disk alloc]initWithNewDisk:disk];
NSLog(#"Disk Name: %#",theDisk.diskName);
NSLog(#"Disk Number: %#",theDisk.diskBSDName);
NSLog(#"Disk Connection Type: %#",theDisk.diskConnection);
NSLog(#"Disk Capacity in Bytes: %#",theDisk.diskTotalCapacityInBytes);
NSLog(#"Volume Name: %#",theDisk.partitionScheme);
//How Do I return "theDisk" from this function?
//[self.arrayOfDisks addObject:theDisk] does not work...complier has problem with use of "self"
}
void diskDisappearedCallback(DADiskRef disk, void* context)
{
NSLog(#"%s was ejected", DADiskGetBSDName(disk));
}
#end
As you can see, everything logs okay. The issue is that I want to return "theDisk" object in some way So I can work with it.
Since the callback function is void, I cannot do a return statement. If I attempt to modify the function's return type the DARegisterDiskAppearedCallback Function will not work entirely.
Again, my only goal here is to get information about all disks and partitions on computer and put them in an array so I can get info about them and manipulate them.
Also, can anyone explain when one would put something in "(void*)context" in the callback function? Apple Documentation is very vague on this...or maybe I am missing something entirely
The context parameter is for your use. You can set whatever you want as the context, and DiskArbitration will pass it to you when it calls the callback. You can use this to solve your first problem by passing your DiskDetector object as the context:
-(id)init {
// ...
DARegisterDiskAppearedCallback(session, kDADiskDescriptionMatchVolumeMountable, diskAppearedCallback, self);
// ...
}
void diskAppearedCallback(DADiskRef disk, void* context) {
DiskDetector *detector = (DiskDetector *)context;
// ...
[detector.arrayOfDisks addObject:theDisk];
}

Doing an atomic read in objective-C

I have a thread-safe class, a cancel token, that transitions from an unstable mutable state (not cancelled) to a stable immutable state (cancelled). Once an instance has become immutable, I'd like to stop paying the cost of acquiring a lock before checking the state.
Here's a simplification of what things look like now:
-(bool) isCancelled {
#synchronized(self) {
return _isCancelled;
}
}
-(bool) tryCancel {
#synchronized(self) {
if (_isCancelled) return false;
_isCancelled = true;
}
return true;
}
and what I want to try:
-(bool) isCancelled {
bool result;
// is the following correct?
// can the two full barriers be reduced to a single read-acquire barrier somehow?
OSMemoryBarrier();
result = _isCancelled != 0;
OSMemoryBarrier();
return result;
}
-(bool) tryCancel {
return OSAtomicCompareAndSwap32Barrier(0, 1, &_isCancelled);
}
Is using two memory barriers the correct approach? How should I expect it to compare to the cost of acquiring a lock (insert standard refrain about profiling here)? Is there a cheaper way to do it?
Edit: this sounds like possible premature optimization. is this lock acquisition slowing things down?
Edit2: its possible compiler optimization will defeat this. be aware.
if you are concerned about the gotchas with double checked locking, perhaps dispatch_once() could be useful for you?
would double checked locking work in this case?
-(void) doSomething {
if (!_isCanceled) { //only attempt to acquire lock if not canceled already
#synchronized(self) {
if (!_isCanceled) // now check again (the double check part)
doSomethingElse();
}
}
}
read the wikipedia entry on double checked locking for more info

How to enforce parameters of anonymous blocks to be unused in Objective-C?

I've run into a situation while using a library called TransitionKit (helps you write state machines) where I am want to supply entry and exit actions in the form of a callback.
Sadly, the callbacks include two completely useless parameters. A typical block has to look like this:
^void (TKState *state, TKStateMachine *stateMachine) {
// I TOTALLY don't want parameters `state` or `stateMachine` used here
};
(this is an anonymous code block. Read up on blocks here if you're unclear)
As I've noted in the comment, I really don't want those parameters even mentioned in the body there. I've tried simply removing the parameter names like suggested in this question like so:
^void (TKState *, TKStateMachine *) {
// I foobar all I like here
};
but sadly the code won't compile then :(.
How can I enforce this non-usage of parameters in code?
This is what I could come up with. Quite a hack and relies on the GCC poison pragma, which is not standard but a GNU extension - although, given that you are probably compiling this with clang anyway, it should not be a problem.
#define _state state
#define _stateMachine stateMachine
#pragma GCC poison state stateMachine
Then this compiles:
^(TKState *_state, TKStateMachine *_stateMachine) {
do_something();
}
But this doesn't:
^(TKState *_state, TKStateMachine *_stateMachine) {
do_something(state, stateMachine);
}
You could just have a function that took one kind of block, and returned another, like this:
#class TKState, TKStateMachine; // here so this will compile
typedef void (^LongStateBlock)(TKState *state, TKStateMachine *stateMachine);
static inline LongStateBlock Adapter(void(^block)()) {
void(^heapBlock)() = [block copy]; // forces block to be on heap rather than stack, a one-time expense
LongStateBlock longBlock = ^(TKState *s __unused, TKStateMachine *sm __unused) {
heapBlock();
};
// this is the non-ARC, MRR version; I'll leave ARC for the interested observer
[heapBlock release];
return [[longBlock copy] autorelease];
}
And in practice:
// this represents a library method
- (void)takesLongStateBlock:(LongStateBlock)longBlock
{
// which hopefully wouldn't look exactly like this
if (longBlock) longBlock(nil, nil);
}
- (void)yourRandomMethod
{
[self takesLongStateBlock:^(TKState *state, TKStateMachine *stateMachine) {
NSLog(#"Gratuitous parameters, AAAAHHHH!");
}];
[self takesLongStateBlock:Adapter(^{
NSLog(#"So, so clean.");
})];
}
The whole thing is gisted, and should compile inside any class. It does what you expect when you call -yourRandomMethod.
AFAIK there is no way to do what you want when you are creating a block, you can only miss the parameter names when you are declaring a block variable(a reference to a block, to avoid misunderstandings)
So here you can miss the param names:
void (^myBlock)(SomeClass *);
But not when you create a block:
myBlock = ^(SomeClass *o)
{
};
I'd write
^void (TKState *unused_state, TKStateMachine *unused_stateMachine) {
// Anyone using unused_state or unused_stateMachine gets what they deserve.
};
Of course someone can use the parameters. But then whatever you do, they can change the code. If someone is intent on shooting themselves in the foot, there is no stopping them.

An example of how to use block response in Restkit?

Instead of a clustered:
- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects
{
if (objectLoader.method == RKRequestMethodGET) {
if ([objectLoader.resourcePath isEqualToString:#"/blah"]) {
// ...
}
} else if (objectLoader.method == RKRequestMethodPUT) {
if ([objectLoader.resourcePath hasSuffix:#"/blahblah"]) {
// ...
}
} else if (objectLoader.method == RKRequestMethodPOST) {
if ([objectLoader.resourcePath isEqualToString:#"/blahblahblah"]) {
// ...
}
}
}
I'd prefer a block approach, especially for simpler requests without any object mapping. Is there any documentation or example of how to use block response?
I don't think there is support for this configuration in the latest (0.10.1) version of RestKit.
There is - (void)loadObjectsAtResourcePath:(NSString *)resourcePath usingBlock:(RKObjectLoaderBlock)block selector, however the block is invoked to allow you to configure the ObjectLoader.
You may also use userData property to distinguish multiple requests, i provided more details in this answer.
With 0.10.1, you can use blocks for POST, GET etc calls, check out this SO answer

How do I use enumerated datatypes in Objective-C?

I'm working on several iOS projects where I think enumerated datatypes would be helpful to me. For example, I have a game where the player can walk in several directions. I could just define four constants with string values as kDirectionUp, kDirectionDown, etc.
I think an enumerated type would be better here. Is that correct? If so, how do I define an enum here so that I can later compare values? (As in, if(someValue == kDirectionUp){})
That sounds like the right thing to do.
It's really simple to create enums in Objective-C using C-style type definitions. For example, in one of my header files, I have the following type definition:
typedef enum {
CFPosterViewTypePoster = 0,
CFPosterViewTypeStart, // 1
CFPosterViewTypeEnd, // 2
.... // 3
} CFPosterViewType;
You define an object of CFPosterViewType and set it to one of the values:
CFPosterViewType posterType = CFPosterViewTypeStart;
When comparing CFPosterViewType values, it's as simple as doing the following:
if (posterType == CFPosterViewTypePoster) {
// do something
}
Note that the commented out numbers in the enum above are implicit values. If you want to do something differently, say, define a bitmask, or anything else where you need the values to be different than the default, you'll need to explicitly define them.
In a header file, define an enum type, e.g.:
// SomeHeaderFile.h
typedef enum {
MOPlayerDirectionNone,
MOPlayerDirectionUp,
MOPlayerDirectionDown,
…
} MOPlayerDirection;
Whenever you need to use MOPlayerDirection, #import that header file. You can then use it as a type as well as its possible values.
For instance:
#import "SomeHeaderFile.h"
#interface MOPlayer : NSObject {
MOPlayerDirection currentDirection;
}
- (void)moveToDirection:(MOPlayerDirection)direction;
- (void)halt;
#end
and:
#import "SomeHeaderFile.h"
#import "MOPlayer.h"
#implementation MOPlayer
- (id)init {
self = [super init];
if (self) {
currentDirection = MOPlayerDirectionNone;
}
return self;
}
- (void)moveToDirection:(MOPlayerDirection)direction {
currentDirection = direction;
switch (currentDirection) {
case MOPlayerDirectionUp:
// do something
break;
case MOPlayerDirectionDown:
// do something
break;
}
}
- (void)halt {
if (currentDirection != MOPlayerDirectionNone) {
// do something
currentDirection = MOPlayerDirectionNone;
}
}
#end
If an enumeration is tightly related to a class, it’s common to define it in the same header file as the class declaration. In the example above, instead of defining MOPlayerDirection in SomeHeaderFile.h, you could define it in MOPlayer.h instead.
Just define them at the top of your file:
enum // direction types
{
kDirectionUp = 0,
kDirectionDown, // 1
kDirectionLeft, // 2
kDirectionRight // 3
};
then you can call as required:
if(someValue == kDirectionUp){ // do something }