如果线程已终止,是否允许重新使用具有相同线程编号的线程?
我编写了一小段代码,如果线程不再繁忙并且已经终止,它会重新使用线程编号。这是代码。它有效,但我想知道我在做什么是允许的吗?
打印出线程id,主循环的当前位置和函数循环的当前位置。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 8
#define NUM_LOOP 17
typedef struct infos {
int mainloop;
int thread_id;
int *busy;
} infos;
void *printtest(void *arg){
int i,sleep;
infos *infostruct=(infos*)(arg);
for (i=0;i<5;i++) {
sleep=rand()%1000000;
printf("thead_id %2i | main %2i | loop: %2i\n",infostruct->thread_id,infostruct->mainloop,i);
usleep( sleep );
}
*infostruct->busy=0;
pthread_exit(0);
}
int main () {
pthread_t threads[NUM_THREADS];
infos infostruct[NUM_LOOP];
int thread_busy[NUM_THREADS]={0},
thread_found,
i,j;
for(i=0;i<NUM_LOOP;i++) {
thread_found=0;
while (thread_found!=1) {
for (j=0;j<NUM_THREADS;j++) {
/* if non-busy thread is found use its number to create a new thread with that number, link the busy variable with the thread_busy array index of the thread.*/
if (thread_busy[j]==0) {
thread_busy[j]=1;
infostruct[i].thread_id=j;
infostruct[i].mainloop=i;
infostruct[i].busy=&thread_busy[j];
if (pthread_create(&threads[j], NULL, printtest, &infostruct[i])) {
printf("ERROR creating thread");
}
pthread_detach(threads[j]);
thread_found=1;
break;
}
}
}
}
for (i=0;i<NUM_THREADS;i++) {
while (thread_busy[i]!=0);
}
printf("\n!!DONE!!\n");
}
答案 0 :(得分:1)
在此代码中,“线程编号”完全是您自己的构造,因此您可以决定如何使用它。