Find the answer to your Linux question:
Results 1 to 3 of 3
Hi, I have a variable of type pthread_t. I want to assign it a value that indicates that this variable does not represent any existing thread - a value that ...
  1. #1
    Just Joined!
    Join Date
    Jun 2008
    Posts
    2

    pthread_t question

    Hi,
    I have a variable of type pthread_t.
    I want to assign it a value that indicates
    that this variable does not represent any
    existing thread -
    a value that cannot be returned by pthread_create().
    what value is possible?

    Thanks

  2. #2
    Linux Engineer wje_lf's Avatar
    Join Date
    Sep 2007
    Location
    Mariposa
    Posts
    1,192
    It depends on how portable you want your application to be.

    If you just want something quick and dirty, then pthread_t is an integer, and you can get away with assigning -1 to it.

    But if you want something portable and correct, there is no way to do what you want, in the way you want to do it. There is no initialization macro for variables of type pthread_t. The only two ways to assign a value to such variables are the pthread_create() and pthread_self() functions. In fact, you should not even compare two variables of that type for equality with the == operation; you should use function pthread_equal() for that.

    There is a different way to do what you want, but it requires a little programming discipline. Wherever you have a variable of type pthread_t in your program, instead have a struct which has two members. One is of type pthread_t; the other is of type int. That second member should be 0 if the first member has not been initialized, and 1 if it has. If such a struct is a global, be sure the second member is initialized to 0 upon program initialization. If it's a local variable within a function, make sure the second member is initialized to 0 as soon as you enter the function.

    Upon successful return from function pthread_create() or function pthread_self(), set the second member of the struct to 1. Set the second member back to 0 when the first member is no longer meaningful.

    Set the name of the second member to something meaningful like thread_id_is_meaningful. There are people out there who feel that such a way of documenting your program is superior to having a special flag value of a variable which means that the variable is not meaningful.

    Whether that's good programming style or not, you have no choice if you want your POSIX threads program to be portable and "correct".

    Hope this helps.
    --
    Bill

    Old age and treachery will overcome youth and skill.

  3. #3
    Just Joined!
    Join Date
    Jun 2008
    Posts
    2
    great, thanks!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...