firstIndex++;
}
pthread_exit(NULL);
}
int main(void) {
int i, ret;
int threadNum = 2;
myTest * pMyTest = (myTest *)malloc(sizeof(myTest));
pMyTest->dataNum = 100;
pMyTest->input = (int *)malloc(sizeof(int)*pMyTest->dataNum);
pMyTest->output = (int *)malloc(sizeof(int)*pMyTest->dataNum);
for(i=0; i
if(i % 4 == 0)
pMyTest->input[i] = (1 << (i%30)) + 1;
else
pMyTest->input[i] = (7 << (i%16)) + 1;
}
pMyTest->index = (int *)calloc(1, sizeof(int));
pMyTest->threadNum = threadNum;
myTest * inMyTest = (myTest *)malloc(sizeof(myTest)*threadNum);
for(i=0; i
(inMyTest+i)->threadID = i;
}
pthread_t * tid = (pthread_t*)malloc(sizeof(pthread_t)*threadNum);
printf("Begin create pthread.\n");
for(i=0; i
if(ret != 0) {
printf("Create pthread error.\n");
return 0;
}
}
for(i=0; i
free(tid);
free(inMyTest);
free(pMyTest->input);
free(pMyTest->output);
free(pMyTest->index);
free(pMyTest);
return 0;
}
与上篇文章的代码作比较,不同的地方主要在于thread函数中。在这个例子中所需要判断是素数还是合数的数有100个,如果使用动态任务划分,则只有打印出结果我们才能知道哪个线程操作了整型数组中的哪个数。而使用静态任务划分的这个程序规定了线程0处理的下标为0-49,线程1处理的下标为50-99。这就是动态任务划分和静态任务划分的区别。
它们有各自的优缺点。
动态任务划分——
优点:任务结束时间均等
缺点:需要上锁和解锁,有时需要频繁等待
静态任务划分——
优点:任务划分简单,线程之间不需要通信
缺点:有时任务完成时间差距较大。