Home > Net >  How to create n threads, each one creates n - 1 threads
How to create n threads, each one creates n - 1 threads

Time:11-05

I am working with a large project and I am trying to create a test that does the following thing: first, create 5 threads. Each one of this threads will create 4 threads, which in turn each one creates 3 other threads. All this happens until 0 threads. I have _ThreadInit() function used to create a thread:

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

where the 3rd parameter is the output(the thread created).

What am I trying to do is start from a number of threads that have to be created n = 5, the following way:

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

I get stuck here. Please, someone help me understand how it should be done. Thanks^^

CodePudding user response:

Building on Eugene Sh.'s comment, you could create a function that takes a parameter, which is the number of threads to create, that calls itself recursively.

Example using standard C threads:

#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
}

Statistics from running:

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