CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Creating and terminating POSIX threads

Initially, each process comprises a single, default thread. All other threads must be explicitly created at run-time.

The function pthread_create() creates a new thread and marks it as executable. pthread_create() can be called any number of times from anywhere within your code (including from within running threads). pthread_create() accepts the arguments:

  • thread: an opaque, unique identifier for the new thread,
  • attr: an opaque attribute object used to set thread attributes. You can specify a thread attributes object, or NULL for default values.
  • start_routine: the C function (name) that the thread will execute once created.
  • arg: A single argument that may be passed to start_routine(). It is passed by reference as a 'pointer of type void', or NULL used if no argument is passed.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define NUM_THREADS     5

void *hello_world(void *threadid)
{
  printf("Hello World, from thread #%li!\n", (long)threadid);
  pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
  pthread_t threads[NUM_THREADS];

  for(long tid=0 ; tid < NUM_THREADS ; tid++) {
    printf("In main(): creating thread %li\n", tid);

    int err = pthread_create(&threads[tid], NULL, hello_world, (void *)tid);

    if(err != 0) {
      printf("ERROR; return code from pthread_create() is %d\n", err);
      exit(EXIT_FAILURE);
    }
  }

  pthread_exit(NULL);       // as main() is a thread, too
  return 0;
}
prompt> mycc -o try try.c -lpthread
prompt> ./try
In main(): creating thread 0
In main(): creating thread 1
Hello World, from thread #0!
In main(): creating thread 2
Hello World, from thread #1!
In main(): creating thread 3
Hello World, from thread #2!
In main(): creating thread 4
Hello World, from thread #3!
Hello World, from thread #4!

 


CITS2002 Systems Programming, Lecture 20, p7, 9th October 2023.