POSIX : How to create a thread | pthread_create() example & Tutorial

What is thread Posix thread?

Posix threads, referred as pthreads,  it is an execution model that lies independently from a language, as well as a from a execution model. It allows a program to control various different flows of work .

In this article we are going to discuss how to create a thread in C or C++ using POSIX Thread Library on Linux.

Thread operations can able to do  thread creation, termination,scheduling, synchronization, process interaction and data management .Each of thread shares the process address space and can access heap, global and static variables.A thread not able to manage a list of creadted threads,it also not able to know when the thread is creaded.

Create thread using pthread_create():

Every function is a thread,main is also a thread. If we have a function that we want to execute in parallel to main function.

void * threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    // Sleep for 2 seconds
    sleep(2);
    std::cout << "Thread Function :: End" << std::endl;
    return NULL;
}

Here we are using  pthread_create() API to create a thread provided by POSIX.

#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine) (void *), void *arg);

pthread_create() function is used to create or generate a new thread, with attributes mentioned as attr, in a process.

If there is no ant attt or attr is NULL, the default one is used. If the attributes specified by attr are modified later, the thread’s attributes are not affected. Upon successful completion, pthread_create() stores the ID of the created thread in the location referenced by thread.Pointer of the Thread ID, it will update the value in it.

So, now we are going to call pthread_create() by passing function pointer and other arguments .

// Thread id
pthread_t threadId;
// Create a thread that will function threadFunc()
int err = pthread_create(&threadId, NULL, &threadFunc, NULL);
// Check if thread is created sucessfuly

We can use strerror() to get the detail of error.pthread_create() returns the error code . If thread is created  then it will return 0.And if  creation is failed it will return error code .

if (err)
    std::cout << "Thread creation failed : " << strerror(err);
else
    std::cout << "Thread Created with ID : " << threadId << std::endl;

Both the function, main function and other  threads runs  parallelly. But when main function ends it tasks, complete process exits and all the other thread will also  terminated. So  before main function ends we should wait for other threads to exit.Wait for other thread to complete POSIX Library provides a function for it i.e. pthread_join().

// Wait for thread to exit
err = pthread_join(threadId, NULL);
// check if joining is sucessful
if (err)
    std::cout << "Failed to join Thread : " << strerror(err) << std::endl;

It accepts a thread ID and pointer to store the return value from thread.

Below is complete example,

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void * threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    // Sleep for 2 seconds
    sleep(2);
    std::cout << "Thread Function :: End" << std::endl;
    return NULL;
}
int main()
{
    // Thread id
    pthread_t threadId;
    // Create a thread that will function threadFunc()
    int err = pthread_create(&threadId, NULL, &threadFunc, NULL);
    // Check if thread is created sucessfuly
    if (err)
    {
        std::cout << "Thread creation failed : " << strerror(err);
        return err;
    }
    else
        std::cout << "Thread Created with ID : " << threadId << std::endl;
    // Do some stuff in Main Thread
    std::cout << "Waiting for thread to exit" << std::endl;
    // Wait for thread to exit
    err = pthread_join(threadId, NULL);
    // check if joining is sucessful
    if (err)
    {
        std::cout << "Failed to join Thread : " << strerror(err) << std::endl;
        return err;
    }
    std::cout << "Exiting Main" << std::endl;
    return 0;
}

Output:

Thread Created with ID : 140054125654592
Waiting for thread to exit
Thread Function :: Start
Thread Function :: End
Exiting Main

Conclusion:

So in this article we have seen all about threads.We have also seen how to use pthread_create() and pthread_join().