1

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]);
5
  • 1
    How are you initializing your array elements? Jan 27, 2014 at 19:59
  • why would you expect a pthread_t to ever equal zero?
    – Red Alert
    Jan 27, 2014 at 20:04
  • i dont know what a unused pthread_t is equal to
    – Jadelabe
    Jan 27, 2014 at 20:06
  • user[i] = (struct users){i,0,count}; pthread_create(&tid[count], NULL, (void*)Actions, &user[i]);
    – Jadelabe
    Jan 27, 2014 at 20:11
  • Please, edit your question, instead of posting it at the comments. Jan 27, 2014 at 20:14

2 Answers 2

2

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?

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.