// 多核心加速處理函數// 在阻塞期間,建立和處理器核心數相同數量的線程來執行回呼函數// 例如 雙核 會執行下面的方法// pfun(0, 2)// pfun(1, 2)inlinevoid MultiCoreProcessing(void (^pfun)(int i_thread, int num_thread)){ NSUInteger processorCount = [[NSProcessInfo processInfo] processorCount]; //單核CPU直接執行 if (!OPT_MULTICORE || processorCount == 1) { pfun(0, 1); return; } unsigned short int count = processorCount; //訊號量 dispatch_semaphore_t *semPart = (dispatch_semaphore_t*)malloc(sizeof(dispatch_semaphore_t)*count); //啟動 for (int i=0; i<count; i++) { //建立一個等待的訊號量 semPart[i] = dispatch_semaphore_create(0); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(void){ //執行回調方法 pfun(i, count); dispatch_semaphore_signal(semPart[i]); }); } //等待任務結束 for (int i=0; i<count; i++) { dispatch_semaphore_wait(semPart[i], DISPATCH_TIME_FOREVER); dispatch_release(semPart[i]); } free(semPart);}用法:void (^pfun)(int, int) = ^void (int i_thread, int num_thread) { //將圖片資料分割成 num_thread 次執行,每個線程處理一部分資料 TiBitmapData *bitmapPart = SplitBitmap(bitmap, i_thread, num_thread); AdjustVibrance(*bitmapPart, saturation, vibrance); delete bitmapPart; }; MultiCoreProcessing(pfun);