Routine in Pthread

Routine is a context of content that is going to be exectued by a thread. We can simply treat a routine as a function.

To create a routine in Pthread, we could simply declare a void * function with a parameter of type void *. Pass in the function and its parameter into the third and forth parameter of pthread_create correspondingly for the thread to execute. In order get the return value from the function, we need to obtain the value from the second parameter of pthread_join with a casting of void **.

void *routine(void *arg) {
  int value = *((int *)arg);
  value++;
  *((int *)arg) = value;
  return arg;
  // pthread_exit(arg); /// alternative to return
}

// in the main program
int *arg = malloc(sizeof(int));
*arg = 5;
pthread_create(&th, NULL, &routine, (void *)arg);
pthread_join(th, (void **)&arg);
free(arg);

Keep in mind that we need to dynamically allocate memory for the argument and the return value, then free them afterwards. The best practice is to use the same pointer for both the arugment and the return value of the routine.

Be aware that if the argument is access by multiple threads, there will be a concern over 202112061109# if those threads are able to read from and write to the arguments without restriction.

Links to this page
#multithreading #pthread