C Programming

POSIX Thread with C Programming

A thread is a small instance running within a process. Threads combine to create a process, and they have some properties of the process; therefore, they are considered lightweight processes. Thread is not independent, just like a process. Rather they work together to compile and create a process. Still, just like a process, a thread also has its own PC (Program Counter) and a particular register set along with stack space.

POSIX Thread:

In Linux platforms, the C and C++ languages pthread standard API for all kinds of thread related functions. It is also known as a POSIX thread that allows users to create many threads for simultaneous processes to flow. It is best used in multi-core systems or processors to implement threads on the kernel to achieve the system.

Implementation:

It is necessary to include this pthread.h header file in the script initially. This will help in using the functions of the pthreads library. To execute the c file, the following commands

$ cc -pthread file.c

OR

$ cc -lpthread file.c

The functions that are defined in the pthreads library can include:

pthread_create:

It is used to create a new thread

Parameters of pthread_create:

It has the following parameters:

thread: This acts as a pointer to an unsigned integer value. It returns the thread id of the thread that is formed.

attributes: This parameter acts as a pointer to a structure. It is used to define attributes of a thread that can be the policy of scheduling, and stack address, etc.

start_routine: This parameter is a pointer to a subroutine implemented by the thread.

argument: This parameter is a pointer to void with different arguments to the function pre-defined at the start of the argument

Syntax:

>> int pthread_create

(pthread_t * thread, const pthread_attributes_t * attr, void * (*start_routine)(void *), void *argument);

pthread_exit:

It is used to terminate or end a thread

Parameters of pthread_exit:

The method used at the end of the method/process accepts a parameter retval that is a compulsory indicator to an integer. It stores the status of the thread such that the thread terminates. It must be a global variable. This will allow the next thread in line to join the thread if it is available.

Syntax:

>> void pthread_exit(void *retval);

pthread_join:

This is a function used at the time of wait for the termination of the thread.

Parameters for pthread_join:

The parameter used here are:

thread_id: It is the ID of the thread for which the thread in line waits.

thread_return: It is the parameter that acts as a pointer to the particular location where we have defined the exit status.

Syntax:

>> int pthread_join(pthread_t thread_identification, void **thread_return);

pthread_self:

This is a method used to get the id of the thread currently in line.

Syntax:

>> pthread_t pthread_self(void);

pthread_equal:

This method is used to compare in case two threads are equivalent or not. If two threads are alike, then the function will return a value other than zero in response.

Syntax:

>> int pthread_equal(pthread_t thread1, pthread_t thread2);

pthread_cancel:

This method is used to send a request for cancellation

Parameter for pthread_cancel:

The parameter used is mandatory to be entered to cancel the request.

Syntax:

>> int pthread_cancel(pthread_t threadName);

pthread_detach:

This is the method that is used to separate a thread. It does not need any thread to join on the termination. All of the resources running in the thread are released as soon as the thread is detached.

Parameter of pthread_detachr:

It is the parameter that accepts the mandatory parameter thread id. It is a must to be detached.

Syntax:

>> int pthread_detach(pthread_t thread);

Sample code:

Here is an example code to show the implementation of the above-described function. We used a gcc compiler to compile these functions.

// Program to show the thread functions

#include<stdio.h>

#include<pthread.h>

#include<stdlib.h>

// Calling the POSIX thread, a must-have in UNIX/LINUX systems

pthread_t tid[2];

void*Function(void *arg)

{

    unsigned long i = 0;

    pthread_t id = pthread_self();

    if(pthread_equal(id,tid[0]))

// Condition for threads being equal

    {

        printf("\n First thread is being processed\n");

    }

    else

    {

        printf("\n Second thread is being processed \n");

    }

// Threads being processed.

    for(i=0; i<(0x255);i++);

    return NULL;

}

int main(void)

{

    int i = 0;

    int error;

// Creating a new thread

    while(i < 2)

    {

        error = pthread_create(&(tid[i]), NULL, &Function, NULL);

        if (error != 0)

            printf("\n Not been able to create the thread :[%s]", strerror(error));

        else

            printf("\n Thread has been created successfully\n");

// Thread created successfully

        i++;

    }

    sleep(5);

    return 0;

}

The code is written in a text editor; you can use any editor based on your choice. Then save it in your favorite location.

The file is saved in the computer system and then is accessed. The file saved by us was named test.c. To access it, type the following command in the terminal window:

$ sudo gcc test.c -lpthread

Next, to execute the output, type the following command:

$ ./a.out

Expected Output:

The output we got in response to the previous code is shown below:

Conclusion:

The tutorial covered the basic process of thread creation and discussed all of the commonly used methods in its creation. Thread is an instance of a process. We then walked users through the famous parameters used by each process along with the syntaxes so that they can make use of them in their computer programs. Here we also shared an example code as a sample to better understand the idea of creating a C program in POSIX. The compiler we used was gcc in the Linux system. Users can opt for any other compiler as well based on their preference.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.