Learning by doing the code is a good way to learn new concept as that said here goes the first multi-threaded C C++ program.

/* www.techybook.in - Sample code 1.1 */

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

void * ThreadEntry(void *arg)
   for(;;) puts("Hello world!");

int main()
   pthread_t tid; /* thread id */
   pthread_create(&tid, 0, ThreadEntry, 0);
   return 0;

First line of the program is a common include header and the second line includes the header pthread.h [ see standard ] which has the implementation of multi-threading related functions. Next line is the definition of ThreadEntry(). Will discuss its purpose shortly as now note down the prototype of the function.

The first line of main function `pthread_t tid;` declares a variable of type pthread_t which is the type used to represent the unique id of each thread created in the application. Second line is the place where the actual thread is created as the function name itself is self explanatory.  The prototype of the function `pthread_create()` [ see standard ] is as follows

int pthread_create(pthread_t *restrict thread,
       const pthread_attr_t *restrict attr,
       void *(*start_routine)(void*), void *restrict arg);

The first argument is the pointer to a variable in which the function will store the id of newly created thread. The second argument is the attribute value used to control the behavior of the newly created. You can learn more about the second argument in later sections of this tutorial.  The third argument says the function where the new thread should start its execution i.e. entry point for the thread. The forth argument is the value that will be passed as argument to the entry function.

1 2