0
Posted January 21, 2011 by Spyros in C/C++ Programming
 
 

Create a Thread Using pThreads in C

threads
threads

Threaded programming is a quite large programming topic on its own. However, little by little, we will get to know of pThreads better. For starters, we will be describing how to create a simple thread using pThreads. Doing so is pretty easy. We just need to use pthread_create() in order to create our new thread. Let’s take a look at the code needed to create a simple thread that just prints a Hello :

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

void *hello(void *simpleInt)
{
    int simple;
    simple = (int)simpleInt;
    printf("Hello From Thread ! I got fed with an integer whose value is %ld!\n", simple);
    pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
    pthread_t thread;
    int rc;
    int number = 3;

    rc = pthread_create(&thread, NULL, hello, (void *)number);

    pthread_exit(NULL);
}

pthread_create gets 4 parameters. The first one is actually an empty variable that is used to store the newly created thread id, once it’s created of course. The second parameters can be used to define some attributes of the created thread. For this simple version of thread creation, it is just used as NULL. The third parameter is the address of the function that will be executed upon thread creation, when the thread starts running. Finally, *t is a void pointer that we use to pass a parameter to the hello() function, which is an integer, having a value of 3, in that case. If we need to add more parameters to that function, we need to do that by passing a struct.

Also notice the usage of pthread_exit(). When used inside the thread body (in hello() function), it exits the thread. However, when it’s used in main(), it’s a bit different. Normally, when main() reaches its end, the whole program terminates. The same would happen with this program but if that happens, all the child threads that were spawned from main(), will violently terminate. Of course, we do not want that to happen. We need our thread to go on executing, even if the main program ends. And this is what pthread_exit does when called right before main returns.


Spyros