Reputation: 37
I am trying to check whether a thread in an array is unused and then return the space of the array unused
int Check(){
int a;
for (a=0;a<12;a++){
if(tid[a]==0){
return a;
}
}
return -1;
tid is a global variable
pthread_t tid[12];
I am always getting the -1 return, I don't know how to check whether the thread is used or not.
I don't know what an unused pthread_t is equal to.
This is how I'm initializing the array:
user[i] = (struct users){i,0,count};
pthread_create(&tid[count], NULL, (void*)Actions, &user[i]);
Upvotes: 1
Views: 1411
Reputation: 58627
Suggestion:
In the main thread, call pthread_self
and capture the return value somewhere; perhaps a global variable.
While the main thread is alive, the ID of any other thread cannot be equal to the ID of the main thread; so you can use this main thread ID as a special value to indicate "no thread here".
/* ... */
no_thread = pthread_self(); /* in main */
/* ... */
if (pthread_create(&tid[i], ...)) {
/* failed */
tid[i] = no_thread;
}
/* ... */
if (pthread_equal(tid[i], no_thread)) {
/* no thread at index i */
}
The alternative is to have a parallel array tid_valid[]
of booleans which indicate the validity of the corresponding tid
values are present. Or a structure like:
struct thread_info {
pthread_t id;
int valid;
};
and make the tid
array of these structures.
Upvotes: 1
Reputation: 2239
You can not track whether a pthread_t
is being used or not simply by comparing it with a constant like you did. The contents of the pthread_t
data type are purposedly not exposed to the programmer.
Consider declaring your array as an array of the following struct:
typedef struct {
bool avaiable;
pthread_t thread;
} threadrec_t;
Use the threadrec_t.avaiable
field to identify whether the thread is in use or not. You must remember to set its value to true
when giving usage to it, and false
when the job is done.
Take a look at this some what related question:
How do you query a pthread to see if it is still running?
Upvotes: 2