Pthreads are a simple and effective way of creating a multi-threaded application. This introduction to pthreads shows the basic functionality – executing two tasks in parallel and merging back into a single thread when the work has been done.

First I’ll run through the basics of threading applications with pthreads. Multi-threaded applications allow two or more tasks to be executed concurrently (ie: at the same time). When a thread is created using pthread_create, both the original thread and the new thread share the same code base and the same memory – it’s just like making two function calls at the same time. Multi-threaded applications come with a whole host of concurrency issues, which will be discussed further in a future post.

All C programs using pthreads need to include the pthread.h header file (ie: #include <pthread.h>). There are four steps to creating a basic threaded program:

1: Define thread reference variables

The variable type pthread_t is a means of referencing threads. There needs to be a pthread_t variable in existence for every thread being created. Something like pthread_t thread0; will do the trick.

2: Create an entry point for the thread

When creating a thread using pthreads, you need to point it to a function for it to start execution. The function must return void * and take a single void * argument. For example, if you want the function to take an integer argument, you will need to pass the address of the integer and dereference it later. This may sound complicated but, as is shown below, it’s pretty simple. An example function signature would be void *my_entry_function(void *param);

3: Create the thread

Once the pthread_t variable has been defined and the entry point function created, we can create the thread using pthread_create. This method takes four arguments: a pointer to the pthread_t variable, any extra attributes (don’t worry about this for now – just set it to NULL), a pointer to the function to call (ie: the name of the entry point) and the pointer being passed as the argument to the function. Now there’s a lot of pointers in that call, but don’t stress – it’s not as tricky as it sounds. This call will look something like pthread_create(&thread0, NULL, my_entry_function, &parameter);

4: Join everything back up

When the newly-created thread has finished doing it’s bits, we need to join everything back up. This is done by the pthread_join function which takes two parameters: the pthread_t variable used when pthread_create was called (not a pointer this time) and a pointer to the return value pointer (don’t worry about this for now – just set it to NULL). This call will look something like pthread_join(thread0, NULL);

And that’s all there is to it. The function used as the thread entry point can call other functions, create variables or do anything any other function can do. It can also use the variables set by the other thread.

When compiling the program, you will also need to add -lpthread to the compile command. ie: gcc program.c -o program -lpthread

Below is a minimum example of a threaded application. It creates two numbers, x and y, and creates a second thread. The first thread increments y until it has the value of 100, while the second thread increments x until it has the value of 100 at the same time. When this is done, it joins the second thread back with the main program and prints the results. Note how, even though x was changed by the second thread, it has been changed for the main program too!

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

/* this function is run by the second thread */
void *inc_x(void *x_void_ptr)
{

/* increment x to 100 */
int *x_ptr = (int *)x_void_ptr;
while(++(*x_ptr) < 100);

printf("x increment finished\n");

/* the function must return something - NULL will do */
return NULL;

}

int main()
{

int x = 0, y = 0;

/* show the initial values of x and y */
printf("x: %d, y: %d\n", x, y);

/* this variable is our reference to the second thread */
pthread_t inc_x_thread;

/* create a second thread which executes inc_x(&x) */
if(pthread_create(&inc_x_thread, NULL, inc_x, &x)) {

fprintf(stderr, "Error creating thread\n");
return 1;

}
/* increment y to 100 in the first thread */
while(++y < 100);

printf("y increment finished\n");

/* wait for the second thread to finish */
if(pthread_join(inc_x_thread, NULL)) {

fprintf(stderr, "Error joining thread\n");
return 2;

}

/* show the results - x is now 100 thanks to the second thread */
printf("x: %d, y: %d\n", x, y);

return 0;

}

This code will print something like:

x: 0, y:0
y increment finished
x increment finished
x: 100, y: 100

  1. Matt says:

    Nice simple example, thank you.

  2. Priya Wagh says:

    nice example !
    + your site have an awesome theme.

  3. Niklas says:

    Hi Tim,
    thank you very much for this good example. It helped me very much.
    yours
    Niklas

  4. void says:

    Thanx, it helped me

    cheers

  5. fred gannett says:

    Check out Open-MP. Less overheads and more task focused.

  6. void1 says:

    This site was really helpful for doing my intro in pthreads

  7. Lucy says:

    I want to add two numbers using pthread and the result comes back to main…

  8. void2 says:

    Thanks for this very helpful document

  9. gl says:

    very good example. thank you.

  10. tasos says:

    hi! nice code but when i copy paste to backtrack 5 and try to compile its says :
    root@root:~/Desktop# gcc -o tasos1 tasos1.c -Ipthread
    /tmp/ccJoQXZL.o: In function `main’:
    tasos1.c:(.text+0x8c): undefined reference to `pthread_create’
    tasos1.c:(.text+0xee): undefined reference to `pthread_join’
    collect2: ld returned 1 exit status

    what i am doing wrong? please help

  11. Tim says:

    Hi tasos. I’ve never used backtrack 5 so I’m not sure how the link line is specified. It looks like -lpthread is being ignored, or that you’re compiling on a system which does not support pthreads.

  12. undx says:

    Tasos: you’ve a typo in commandline: -l and -I (capital i).
    Tim: excellent post ! Thank you.

  13. Vishal says:

    thanks!
    I had no idea that we could do this using C 🙂

  14. Krzychu says:

    Hi. I have trouble to understand code. Why y increment if as argument to fuction we set x?

    If this create second thread:
    /* create a second thread which executes count_x(&x) */
    if(pthread_create(&inc_x_thread, NULL, inc_x, &x)) {

    when is creating first thread?

  15. Tim says:

    Hi Krzychu.

    The first thread is the main program. the pthread_create call spawns a second thread to increment x, and the first (main) thread increments y. The program will have two threads until the second thread is joined back into the main thread with the pthread_join call.

  16. Carlos says:

    With this two small modification one can be sured the two threads run at the same time:

    /* increment x to 100 */
    while(++(*x_ptr) < 100){
    printf(" x = %d from child\n",*x_ptr);
    }

    and

    /* increment y to 100 in the first thread */
    while(++y < 100){
    printf(" y = %d from parent\n",y);
    }

  17. Some Guy says:

    Thanks, super helpful stuff. Glad you kept it simple and focussed on one thing, since we’re here for just that one thing.

  18. alex says:

    If we wanted to write this using synchronization primitives then what is the changes required

  19. Markus says:

    Very cool intro!!

    Note: If you use mingw in eclipse:
    – be shure you got pthreadGC2.dll in mingw bin folder
    – add a linker Option -lpthreadGC2 at the end (the order is important!)
    otherwise you get
    undefined reference to `_imp__pthread_create’

    modify project->properties->c/c++build->settings->mingwlinker:
    – the command line pattern:
    ${COMMAND} ${OUTPUT_FLAG}${OUTPUT_PREFIX}${OUTPUT} ${INPUTS} ${FLAGS}
    – the micellanous -> linker flags:
    -lpthreadGC2

  20. papi says:

    Salem alikoum(hello for every one),Thank you it helped me,but i have a question:you create a one thread,not two ???

  21. Orion says:

    Thankyou ! great example !

  22. packiya lakshmi says:

    thanks… really helfull for students those who are new to threads.

  23. Erlind says:

    I have problems when i compile in Dev C++, it shows me debugs like this:
    28 C:\Users\lindi\Documents\Thread.cpp `pthread_t’ undeclared (first use this function)
    (Each undeclared identifier is reported only once for each function it appears in.)
    31 C:\Users\lindi\Documents\Thread.cpp `inc_x_thread’ undeclared (first use this function)

    What should i do?

  24. bakalolo says:

    awesome tutorial!

  25. […] the example I grabbed, and many thanks to Tim Murphy for writing a simple, good pthread example: PThreads in C – A Minimal Working Example. What I changed is in the *inc_x() function just after the declaration for int *x_ptr and […]

  26. Hari Kishan says:

    A very simple and straight forward example for quick learners. Thank you.

  27. navya says:

    it is really helpful, thanks for this information..
    can u tell me, while creating the thread, what is that second argument implies?
    thanks in advance.

  28. Aarti says:

    very well explained sir..
    but i am nt able to understand why we are using threading in our program..

  29. nice Example We can Easily Understand the concept of threads.

    Really Good…!!!!

  30. Hanumant says:

    very nice example thanks a lot .

  31. Hiren says:

    i’m working on multitasking but i have not library file pthread.h so, is any solution you have for this problem ? if you have libreary file than send me on my email hiren.tejani@energycloud.co.in

  32. chris. says:

    Short and sweet, excellent and clear reading.

  33. Maya says:

    Thanks for this, the clarity is really appreciated.

  34. anonymous says:

    tried to implement dekker-algorhytm, your example failed

  35. Assaf says:

    hi, the library defines doesn’t work for me.
    #include – it doesn’t work, the visual studio says that he cannot open source file. what to do? thanks for the helpers
    please email me: assafking12@gmail.com

  36. Keerthana Varadarajan says:

    Nice Example . Thankyou !

  37. Praful says:

    #include
    #include
    //#include

    void *fun1(void *arg)
    {

    printf(“1st Thread is created successfully\n”);

    return;

    }
    int main(void)
    {

    pthread_t tid;

    printf(“WEll come to crete a thread\n”);

    //Pthread used to create thread;
    // tid is used to store function value;

    pthread_create(&tid,NULL,fun1,NULL);

    pthread_join(tid,NULL);

    return 0;
    }
    this is simple program i may say…

  38. Genaldo Leite Nunes says:

    nice example !!

  39. Leo says:

    Hi, I’m new at this languague. So ?’ve problem. ex: i want to have two thread and ?’ve input.txt:
    10
    20
    30
    40
    ..
    ..
    Then firstly, my one thread add the number one by one in input txt up to down and my another one thread add the number one by one down to up. and in the middle of input returns the totals number each thread and add them. how can ? th?s quest?on ?

  40. anhdt61 says:

    NICE example! thanks for sharing

  41. Safiullah Ayubi says:

    thanx for shearing such a wonderful and simple example

  42. kalai says:

    Can you explain how the compilation is going ?? since am new i got little confused. I understood the theory part well. Its simple and easy . can you tell the compilation order

  43. Evgeny says:

    Thank you!

  44. Hal says:

    Did I miss something — (could have have bad eyesight) —
    Question: what happens when I try to run such a program on a system that does not support ‘threads’ (i.e. no hyperthreading0/

  45. jim says:

    thanks a lot

  46. Mohit Dabas says:

    Simple,Sweet,Elegant,Awesome

  47. Blanka says:

    i think i love you XD

  48. mohammad says:

    so good

  49. Zaid says:

    Thanks bro I will be able to do my homework now