如何并行处理数组 [英] How to process an array IN PARALLEL
问题描述
因此,有多种方法可以通过选择器或代码块来运行数组的所有元素。 makeObjectsPerformSelector:
和更多
如果手边有4或16个核,则您可能希望发送所有处理不同的过程。
即使在iOS上,也最好将它们全部发送出去,或者至少让它们随风吹拂而完成。 / p>
在可可环境中做到这一点的最佳和最简洁的方法是?
再次,如果您想随时将它们发送出去,即 在执行以下指令之前不要等待枚举完成 ,该怎么办... ?
如果您可以定位iOS 4+或Mac OS X 10.6+,请使用Grand Central Dispatch(我正在使用一个类别,因为我认为它们很酷):
#import< dispatch / dispatch.h>
@interface NSArray(DDAsynchronousAdditions)
-(void)makeObjectsPerformSelectorAsynchronously:(SEL)selector;
-(void)makeObjectsPerformSelectorAsynchronously:(SEL)selector withObject:(id)object;
@end
@implementation NSArray(DDAsynchronousAdditions)
-(void)makeObjectsPerformSelectorAsynchronously:(SEL)selector {
[self makeObjectsPerformSelectorAsynchronouslyly :selector withObject:nil];
}
-(void)makeObjectsPerformSelectorAsynchronously:(SEL)selector withObject:(id)object {
for(id id in self){
dispatch_async(dispatch_get_global_queue( 0,0),^ {
[element performSelector:selector withObject:object];
});
}
}
@end
//其他地方:
[myArray makeObjectsPerformSelectorAsynchronously:@selector(doFoo)] ;
或者,如果您不想使用类别...
[myArray enumerateObjectsUsingBlock:^(id obj,NSUInteger index,BOOL * stop){
dispatch_async(dispatch_get_global_queue(0,0),^ {
[obj performSelector:@selector(doFoo)];
};
}];
So there's a number of ways to run all the elements of an array through a selector or block of code. makeObjectsPerformSelector:
and more
If you have 4 or 16 cores on hand, you may well want to send all the processing off to different processes.
Even on iOS, it could well be sensible to send them all away, or at least let them be finished whichever way the wind blows.
What is the best and neatest way to do this in the cocoa milieu?
Again, what if you want to send them away to be finished at any time, i.e., do not wait for the enumeration to finish before executing the following instruction...?
If you can target iOS 4+ or Mac OS X 10.6+, use Grand Central Dispatch (and I'm using a category because I think they're cool):
#import <dispatch/dispatch.h>
@interface NSArray (DDAsynchronousAdditions)
- (void) makeObjectsPerformSelectorAsynchronously:(SEL)selector;
- (void) makeObjectsPerformSelectorAsynchronously:(SEL)selector withObject:(id)object;
@end
@implementation NSArray (DDAsynchronousAdditions)
- (void) makeObjectsPerformSelectorAsynchronously:(SEL)selector {
[self makeObjectsPerformSelectorAsynchronously:selector withObject:nil];
}
- (void) makeObjectsPerformSelectorAsynchronously:(SEL)selector withObject:(id)object {
for (id element in self) {
dispatch_async(dispatch_get_global_queue(0,0), ^{
[element performSelector:selector withObject:object];
});
}
}
@end
//elsewhere:
[myArray makeObjectsPerformSelectorAsynchronously:@selector(doFoo)];
Or, if you don't want to use a category...
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL * stop) {
dispatch_async(dispatch_get_global_queue(0,0), ^{
[obj performSelector:@selector(doFoo)];
};
}];
这篇关于如何并行处理数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!