Reputation: 417
Is it allowed to re-use thread with the same thread number if they have terminated?
I have written a small piece of code which re-uses thread numbers if the threads are no longer busy and have been terminated. Here is the code. It works but I am wondering is if what I am doing is allowed?
It prints out what the thread id, the current position of the main loop and the the current position of the function loop is.
#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");
}
Upvotes: 0
Views: 148
Reputation: 13016
In this code, the "thread number" is entirely your own construct, so you can decide on the rules for how it should be used.
Upvotes: 1