如何在没有循环的情况下递归创建线程

时间:2015-10-29 09:40:52

标签: pthreads

我想创建一个代码: 在不使用循环的情况下创建递归线程,线程必须执行某些例程。我在ubuntu上使用Pthread_create

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 8

void *PrintHello(void *threadid)
{
  printf("\n%d: Hello World!\n", threadid);
  pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
  pthread_t threads[NUM_THREADS];
  int rc, t;
  for(t=0; t<NUM_THREADS; t++)
  {
    printf("Creating thread %d\n", t);
    rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
    if (rc)
    {
      printf("ERROR; return code from pthread_create() is %d\n", rc);
      exit(-1);
    }
  }
  pthread_exit(NULL);
} 

1 个答案:

答案 0 :(得分:0)

是的,您可以在不使用for循环的情况下创建线程,我已修改您的代码并使用函数递归来创建pthread ..

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 8
pthread_t threads[NUM_THREADS];

void *PrintHello(void *threadid)
{
    printf("\n%d: Hello World!\n", threadid);
    pthread_exit(NULL);
}

void create_thread(int n){

    if (n > 0 ){  
        //Create thread 
        printf("Creating thread %d\n", ((NUM_THREADS - n) + 1) );
        //NUM_THREADS - n to start index from 0 
        int rc = pthread_create(&threads[NUM_THREADS - n], NULL, PrintHello, (void *)(NUM_THREADS - n));
        if (rc)
        {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
        n--;
        create_thread(n);
    }   
    return;
}

int main(int argc, char *argv[])
{

    int rc, t;

    create_thread( NUM_THREADS );

    //Wait to finish all thread
    for (t = 0; t < NUM_THREADS; t++)
    {
        pthread_join(threads[t],NULL);
    }

    pthread_exit(NULL);
    return 0;

}

希望这会对你有所帮助。

相关问题