Pthreads 如何在没有循环的情况下递归创建线程
我想创建一个代码,它将: 在不使用循环的情况下创建递归线程,线程必须执行某些例程。我正在ubuntu上使用Pthread_createPthreads 如何在没有循环的情况下递归创建线程,pthreads,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
#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);
}
是的,您可以在不使用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;
}
希望这对您有所帮助。您尝试过什么?你的具体问题是什么?查看有关如何提出好问题的更多信息。很抱歉,如果这是一个混淆,我下面的代码应该创建8个线程并使用线程ID打印Hello World,我想使用for Loop对递归执行同样的操作。请编辑您的问题并在那里添加代码,而不是将其添加为注释。很抱歉,我不熟悉C编程和论坛。谢谢你的理解