The start_routine( ) function run by a thread

  • Recall the syntax of the pthread_create( ) function:

      int pthread_create(pthread_t *threadID, const pthread_attr_t *attr,
                         void *(*start_routine) (void *), void *arg);
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

  • The start_routine( ) function in the pthread_create( ) call was defined as:

       void * (*start_routine) ( void * ) 
       ^^^^^^                    ^^^^^^
      return type             parameter type
    

  • I.e.: the start_routine( ) function has the following form:

      void * functionName( void *arg )
      {
          ....
      }
    

    The data type void * is a "general purpose" pointer type

Defining a start_routine with a argument

  • The start_routine( ) function of a thread can have an arbitrary pointer type parameter

  • Example: a start_routine( ) function named worker( ) with an int * parameter:

     void *worker(void *arg)
     {
         int *p;     // Pointer (reference, address) to an integer variable
         int x;      // An integer variable
    
         p = (int *) arg;   // Cast "(void *)" type to "(int *)"
         x = *p             // Retrieve the int value in arg
    
         printf("arg = %d\n", x);
         return(NULL);      // Thread exits
     }  
    

    Note:

    • Technically, we are retrieving the integer value from *arg like this:

        int x = *arg;  // But this syntax is illegal
                       // because arg's data type is void * (unknown)
      		 // We need to cast to an int * first !
      

Passing an pointer argumenet to the start_routine( ) of a thread

  • You can pass the address of a variable of any data type as an argument to the start_routine( ) of a thread

  • Example: pass the address of an int variable to the start_routine( ) of a thread

     int main(int argc, char *argv[])
     {
         pthread_t  tid;
         int        param;         // Integer
    
         param = 12345;            // Initialize param var
    
         pthread_create(&tid, NULL, worker, &param);
    
         sleep(1);
     }

    When the worker( ) function is executed by the new thread, the arg of the worker( ) function will contain the value 12345

DEMO: demo/pthread/param.c