【问题标题】:How to create n threads, each one creates n - 1 threads如何创建 n 个线程,每个线程创建 n - 1 个线程
【发布时间】:2021-12-18 02:06:00
【问题描述】:

我正在处理一个大型项目,我正在尝试创建一个执行以下操作的测试:首先,创建 5 个线程。每个线程将创建 4 个线程,每个线程又创建 3 个其他线程。这一切都发生在 0 个线程之前。 我有 _ThreadInit() 函数用于创建线程:

status = _ThreadInit(mainThreadName, ThreadPriorityDefault, &pThread, FALSE);

第三个参数是输出(创建的线程)。

我想做的是从必须创建的多个线程开始n = 5,方法如下:

for(int i = 0; i < n; i++){
   // here call the _ThreadInit method which creates a thread
}

我卡在这里了。请有人帮我理解应该如何做。谢谢^^

【问题讨论】:

  • 创建一个函数MyCoolThread,它将以要创建的线程数作为参数。这个函数将创建那么多线程,同时将自己作为一个参数少一个的线程函数传递。和递归差不多。

标签: c multithreading


【解决方案1】:

根据 Eugene Sh. 的评论,您可以创建一个函数,该函数接受一个参数,即要创建的线程数,递归调用自身。

使用标准 C 线程的示例:

#include <stdbool.h>
#include <stdio.h>
#include <threads.h>

int MyCoolThread(void *arg) {
    int num = *((int*)arg);     // cast void* to int* and dereference

    printf("got %d\n", num);

    if(num > 0) {               // should we start any threads at all?
        thrd_t pool[num];
        int next_num = num - 1; // how many threads the started threads should start

        for(int t = 0; t < num; ++t) { // loop and create threads
            // Below, MyCoolThread creates a thread that executes MyCoolThread:

            if(thrd_create(&pool[t], MyCoolThread, &next_num) != thrd_success) {

                // We failed to create a thread, set `num` to the number of 
                // threads we actually created and break out.

                num = t;
                break;
            }
        }

        int result;

        for(int t = 0; t < num; ++t) {   // join all the started threads
            thrd_join(pool[t], &result);
        }
    }

    return 0;
}

int main() {
    int num = 5;
    MyCoolThread(&num); // fire it up
}

运行统计:

      1 thread  got 5
      5 threads got 4
     20 threads got 3
     60 threads got 2
    120 threads got 1
    120 threads got 0

【讨论】:

  • 这很有帮助,问题是我必须使用一些预定义的函数。 _ThreadInit 就是其中之一。我不能使用 thrd_create 或 thrd_join,这就是为什么我觉得很难解决这个问题
  • @Gloria 我明白了。我不知道我使用过的任何线程库中的_ThreadInit - 但该算法应该可以与任何线程库重用。以 n=5 作为参数创建第一个线程,然后使用相同的线程启动函数循环并创建 n-1 个线程。完成后,加入所有已启动的线程。
  • @Gloria 我对_ThreadInit 很好奇,想查找有关它的信息。线程库的名称是什么?你有关于这个库的任何在线文档的链接吗?
  • 不,不是。反正没有什么公开的
  • @Gloria 好的。太糟糕了,他们没有先教你标准的东西,然后再教你特殊的库:-(你有没有成功地将答案中的想法转换为你使用的线程库?我漂亮 确保它会以一种或另一种方式支持我在答案中提出的内容。
猜你喜欢
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-10
  • 2021-12-30
相关资源
最近更新 更多