我想在我的 6 核计算机中运行(比如说)25 个 CPU 密集型任务,每次使用 5 个核(所以留 1 个用于其他任务)。25 个 CPU 密集型任务中的每一个都可以在不同的时间完成,例如,一个任务可以在 20 分钟内完成,而另一个任务可能需要长达 4 小时。
使用 pthreads 我设法构建了一个非常简单的算法,它可以启动 5 个线程,等待其完成并再次启动另外 5 个线程。该算法的弱点是它不能利用不同线程可能在不同时间完成的事实,而是总是等待所有 5 个线程的作业完成,然后再启动另一组。
这是启动线程的代码摘录
#define MAX_REACTOR_THREADS 5
/* ....................... */
/* SOME LENGTHY STUFF HERE */
/* ....................... */
int cases = 25;
pthread_t *threads_REACTOR = calloc(cases, sizeof(pthread_t));
int index = 0;
/* CALL THREADS PROCEDURE FOR COMPUTING FUNCTION: REACTOR_THREAD */
int int_div = cases/MAX_REACTOR_THREADS;
int I, k;
for (I=0; I<int_div; I++){
/* LAUNCH THREADS */
for(k=0; k<MAX_REACTOR_THREADS; k++){
index = int_div*k+I;
pthread_create(&threads_REACTOR[index], NULL,
&REACTOR_THREAD, (void*) &inputs_array[index]);
}
/* JOIN THREADS */
for(k=0; k<MAX_REACTOR_THREADS; k++){
index = int_div*k+I;
pthread_join(threads_REACTOR[index], NULL);
}
/* HERE PRINT PROGRESS BAR */
Progress_Bar((I+1)*MAX_REACTOR_THREADS, cases, 40, COLOR_Y);
}
if((cases%MAX_REACTOR_THREADS) != 0){
/* LAUNCH REMAINING THREADS */
for(index=MAX_REACTOR_THREADS*int_div; index<cases; index++){
pthread_create(&threads_REACTOR[index], NULL,
&REACTOR_THREAD, (void*) &inputs_array[index]);
}
/* JOIN REMAINING THREADS */
for(index=MAX_REACTOR_THREADS*int_div; index<cases; index++){
pthread_join(threads_REACTOR[index], NULL);
/* HERE PRINT PROGRESS BAR */
Progress_Bar(index+1, cases, 40, COLOR_Y);
}
}
/* ....................... */
/* SOME LENGTHY STUFF HERE */
/* ....................... */
如何改进这一点,以便它可以在线程完成其工作的那一刻启动新任务?