C、运行n个线程当1个完成作业创建其他线程

C, run n numbers of threads when 1 finish job create other thread

我想产生 N 个执行函数的线程我是这样做的

for (int p = 0; p < threads; p++)
       pthread_create(&tid[p], NULL, dowork, full); 

现在我用

for (int p = 0; p < threads; p++)
       pthread_join(tid[p], NULL);

再次生成 n 个线程,但我想在创建的线程之一完成时生成另一个线程。 例如我有 3 个线程来做 6 个工作(运行 相同的函数 6 次不同的参数) 如果其中一个线程完成,我将创建 3 个线程,然后立即创建另一个线程,而无需等待所有线程完成。 我该怎么做?

以下是固定线程循环的简单解决方案。如果每个任务的运行时间差不多就好了。

将每行注释当成一段代码。

int finished_tasks = 0;
int threads = 3;
int todo_tasks = 6;
int check_index = 0;
// ...

// Create thread by variable `threads` ... 
for (int p = 0; p < threads; p++)
       pthread_create(&tid[p], NULL, dowork, full); 

while( finished_tasks < todo_tasks ){
    // Join one thread by check index;
    // finished_tasks++;
    // Check if finished tasks meets todo tasks, leave the while
    // Immediately create a new thread to do jobs
    // Move check index to next one.
}

既然一个线程完成了,马上又创建了另一个线程。线程总数固定为 threads.

专业版

  • 简单

反对

  • 运行线程偏离1~threads。因为 while 循环总是在等待当前线程的加入,而其他线程可能比当前线程完成得更快。

如果每个任务的操作时间相似,这个解决方案就足够了。但是如果运行时间偏差过大,需要同步检查哪个线程先完成。