【问题标题】:C, run n numbers of threads when 1 finish job create other threadC、当 1 个完成作业创建其他线程时运行 n 个线程
【发布时间】:2020-09-15 01:49:23
【问题描述】:

我想生成 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 个线程,立即创建另一个线程,而无需等待所有线程完成。 我该怎么做?

【问题讨论】:

  • 为什么另一个线程而不是每个线程只是做更多的工作然后终止?
  • 这样也可以,但我不知道特定线程何时结束
  • 加入的问题是你会知道它们什么时候全部完成,但如果它们无序完成,你就无法知道。与其在线程和原子/互斥体/锁之间传递消息使代码复杂化,不如在每个线程中做更多的工作并称之为完成。
  • 一旦线程完成,pthread_join 就会被解除阻塞。因此,您可以添加另一个线程来完成这项工作。这很简单,但您可能不知道哪个线程完成得最快。只要知道加入的线程就完成了。
  • 我不在乎哪个完成得更快,我只想知道 3 个线程中的 1 个是否完成了,但线程数未知

标签: c multithreading pthreads


【解决方案1】:

以下是固定线程循环的简单解决方案。如果每个任务的操作时间都差不多就足够了。

将每一行注释作为一个sn-p代码。

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 循环一直在等待当前线程加入,而其他线程可能比当前线程完成得更快。

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

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2019-06-22
    • 1970-01-01
    相关资源
    最近更新 更多