如何解决C,当1个作业完成创建其他线程时,运行n个线程
我想产生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循环始终在等待当前线程加入,而其他线程的完成速度可能比当前线程快。
如果每个任务具有相似的操作时间,则此解决方案就足够了。但是,如果操作时间偏差太大,则需要进行同步以检查首先完成哪个线程。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。