Re: Threadsafe copy of objective c object
Re: Threadsafe copy of objective c object
- Subject: Re: Threadsafe copy of objective c object
- From: Jeff Kelley <email@hidden>
- Date: Tue, 03 Sep 2013 10:26:53 -0400
You could use a dedicated dispatch queue for all property access and use
dispatch barriers to restrict access to the queue for writes, while still
allowing simultaneous reads.
In -copy:
- (id)copy
{
__block __typeof(self) copy;
dispatch_async(self.propertyQueue, ^{
copy = [[[self class] alloc] init];
// Copy properties here
});
return copy;
}
This assumes a property called propertyQueue:
@property (readonly, nonatomic) dispatch_queue_t propertyQueue;
- (dispatch_queue_t)propertyQueue
{
if (!_propertyQueue) {
_propertyQueue = dispatch_queue_create("queue name here",
DISPATCH_QUEUE_CONCURRENT);
}
return _propertyQueue;
}
In your property getters:
- (int)count
{
__block int count;
dispatch_async(self.propertyQueue, ^{
count = _count;
});
return count;
}
And finally, in your property *setters*:
- (void)setCount:(int)count
{
dispatch_barrier_async(self.propertyQueue, ^{
_count = count;
});
}
Hope this helps!
(Note: all code was typed in the e-mail, so may not compile.)
Jeff Kelley
On Tue, Sep 3, 2013 at 9:34 AM, Jonathan Taylor <
email@hidden> wrote:
> Ah. In my original email I didn't explain *why* it is that "ideally I
> would like to make the copy on a thread other than the main thread". The
> algorithm is doing real-time video processing, and I very much want to
> avoid holding up anything in that code path by synchronizing with the main
> queue. Past experience has shown that that does lead to glitches I am keen
> to avoid. So, while I'm a big fan of such constructions, I'm deliberately
> trying to avoid that here.
>
> Serializing access to MyParameters will work, it's just a shame that there
> isn't such a tidy way of achieving that...
>
>
> On 3 Sep 2013, at 14:18, Robert Vojta wrote:
>
> > Then this should be enough ...
> >
> > - (MyParameters *)copyParameters {
> > __block MyParameters *parameters;
> > dispatch_sync( dispatch_get_main_queue(), ^{
> > parameters = [myObjectHoldingParameters.parameters copy];
> > });
> > return parameters;
> > }
> >
> > ... if all your parameters object properties are set on the main thread
> only.
> >
>
>
> _______________________________________________
>
> Cocoa-dev mailing list (email@hidden)
>
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>
> Help/Unsubscribe/Update your Subscription:
>
> This email sent to email@hidden
>
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden