パラメータや環境変数を含む独立したプロセスを起動するために使用するのに適したクラスはNSTaskです。厄介な詳細については、ドキュメントを参照してください。これは、10個の並行プロセスを開始し、それらが終了するのを待つ小さなコマンドラインツールです。タスクはすでに同時に起動されているため、NSOperationQueueはここでは冗長になります。
-編集:同時実行が制限された改良バージョン-
int main (int argc, const char * argv[])
{
@autoreleasepool {
// Let's not have more than 5 parallel processes
dispatch_semaphore_t limit = dispatch_semaphore_create(5);
dispatch_semaphore_t done = dispatch_semaphore_create(0);
for (int i=0; i<10; i++) {
// Setup the taks as you see fit including the environment variables.
// See docs on NSTask for more on how to use this object.
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/bin/ls";
task.arguments = [NSArray arrayWithObject:@"-la"];
task.terminationHandler = ^(NSTask *task) {
dispatch_semaphore_signal(limit);
if (i==9) dispatch_semaphore_signal(done);
};
dispatch_semaphore_wait(limit, DISPATCH_TIME_FOREVER);
[task launch];
}
dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER);
dispatch_release(limit);
dispatch_release(done);
}
return 0;
}
- 元のバージョン -
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSObject *lock = [[NSObject alloc] init];
int __block counter = 10;
for (int i=0; i<10; i++) {
// Setup the taks as you see fit including the environment variables.
// See docs on NSTask for more on how to use this object.
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/bin/ls";
task.arguments = [NSArray arrayWithObject:@"-la"];
task.terminationHandler = ^(NSTask *task) {
@synchronized(lock) { counter--; }
};
[task launch];
}
while (counter)
usleep(50);
[lock release];
}
return 0;
}
あなたの場合、管理を容易にするためにNSTaskオブジェクトを配列に保持したい場合があります。