PThread library

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • digi123
    New Member
    • Jan 2009
    • 4

    PThread library

    I would like to ask that PrintHello accepts a void pointer but how come you can equate it to an integer directly ???
    " tid = (int)threadid; "
    while at the same time instead if a pointer a normal variable was passed into this function
    " pthread_create( &threads[t], NULL, PrintHello, (void *)t); "

    the above construct is taken from


    Code:
    #include <pthread.h>
    #include <stdio.h>
    #define NUM_THREADS 5
    
    void *PrintHello(void *threadid)
    {
    int tid;
    tid = (int)threadid;
    printf("Hello World! It's me, thread #%d!\n", tid);
    pthread_exit(NULL);
    }
    
    int main (int argc, char *argv[])
    {
    pthread_t threads[NUM_THREADS];
    int rc, t;
    for(t=0; t<NUM_THREADS; t++){
    printf("In main: creating thread %d\n", t);
    rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
    if (rc){
    printf("ERROR; return code from pthread_create() is %d\n", rc);
    exit(-1);
    }
    }
    pthread_exit(NULL);
    }
    Last edited by JosAH; Jan 27 '09, 04:21 PM. Reason: fixed the [code] ... [/code] tags
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by digi123
    I would like to ask that PrintHello accepts a void pointer but how come you can equate it to an integer directly ???
    When you create a thread you can pass the address of a thread local chunk of memory to the newly created thread. The author of the example code wanted to have a cheap thread identification so s/he passed a simple integer.

    A struct with an int containing the thread id could've been passed instead but this code saves a few lines I guess. Note that the conversion from an int to a void pointer (and vice versa) is implementation defined.

    kind regards,

    Jos

    Comment

    • digi123
      New Member
      • Jan 2009
      • 4

      #3
      thanks i got my answer ------
      i hope you meant to say 'undefined' i guess

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by digi123
        thanks i got my answer ------
        i hope you meant to say 'undefined' i guess
        Nope, I meant "implementa tion defined", i.e. an implementation can convert between the two types however it pleases but it should do it consistently.

        kind regards,

        Jos

        Comment

        • digi123
          New Member
          • Jan 2009
          • 4

          #5
          thank you sir,
          i got whole new perspective to look at

          Comment

          Working...