上一贴介绍了比较常见的基于旋锁的并行计算方法。这里将介绍另一种无锁的并行计算方法。两者各有利弊。
同样是计算一个数组,在Blackfin561双核DSP中,可以利用两个核对一个数组进行同时计算,其中一个核计算该数组的前50个元素,另一个核计算该数组的后50个元素。
下面贴除源代码:
// 在共享存储区 // shared.c int resultA =0, resultB =0; int progress =0; int array[100]; // 核A // main.cpp externint array[100]; externint resultA, resultB, progress; int main(void) ...{ // initialize the array for(int i=0; i<100; i++) array[i] = i +1; register int result =0; SICA_SYSCR &=~0x20; // Enable and activate core B for(int i=0; i<50; i++) result += array[i]; // calculate first 50 elements resultA = result; progress++; // this subtask has been completed while(progress <2); // wait for the other subtask TRACE("The answer is: %d ", resultA + resultB); return0; } // 核B // main.cpp externint array[100]; externint resultB, progress; int main(void) ...{ register int result =0; for(int i=50; i<100; i++) result += array[i]; // calculate last 50 elements resultB = result; progress++; return0; }