C Programming

Pthread_Function() in C Language

The POSIX standard gives us the possibility to develop multithreaded programs in the C language. This programming technique consists of using the “pthread” library to open one or more subprocess threads that run in parallel with the main process.

The implementation of threads brings great benefits to the final program since it speeds up the execution times by running multiple tasks simultaneously, can be better structured, and makes a better use of system resources.

A thread is created with the pthread_ create() function. Once this function is called, the thread starts running in parallel with the main process. When this function is called, it returns the thread ID in the output argument thread. This identifier is used to refer to the created thread when you use the thread management functions like pthread_join() or pthread_cancel().

In this Linux Hint article, you will learn how to use the pthread_cancel() function, one of the C thread management functions that lets you cancel a thread that is already running.

Syntax of the Pthread_Cancel() Function in C Language

int pthread_cancel(pthread_t thread);

Description of the Pthread_Cancel() Function in C Language

The pthread_cancel() function sends a request to the system to cancel the thread that is specified by the identifier in its input argument thread.

The call to the pthread_cancel() function does not imply immediate termination of the thread, but a request to do so. Whether a thread is terminated after calling this function depends on the attributes that are assigned to it when it is created. If a thread is created with its default attributes, it can be cancelled.

The cancel attributes of a thread can be retrieved with the pthread_setcancelstate() function and can be set with pthread_setcanceltype().

If the pthread_cancel() function is successful, it returns 0 as the result. If it fails, it returns a nonzero value.

The pthread_cancel() function from the pthread library is defined in the “thread.h” header. To use this and the other thread management functions, you must include this header in your program as follows:

#include <pthread.h>

The programs that use the thread management functions must be compiled by calling the thread library from the Linux command line. Otherwise, the errors will occur.

The following is a special section that explains how to correctly compile the programs that use the functions from the thread library.

How to Cancel a Running Thread Using the Pthread_Cancel() Function in C Language

In this example, we create a thread with the pthread_create() function and then cancel it in the middle of execution with the pthread_cancel() function.

To do this, we create the “thread_1” thread which executes the th_function() function which consists of a for loop with 10 cycles, each of which prints the “Seconds from init thread and the number of seconds elapsed” sentence in the command console. After that, a delay of 1 second is inserted to repeat the cycle again. So, the execution time of the thread is about 10 seconds.

Once thread_1 is created and running, we introduce a 5-second delay via the main() function and terminate the subprocess after half the execution time. To terminate the thread, we call the pthread_cancel() function and pass the thread_1 identifier that is returned by the pthread_create() function as input argument when the thread is created. Now, let us look at the code for this example:

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <pthread.h>

void * th_function (void * n);

void  main()
{
pthread_t thread_1;
pthread_create(&thread_1, NULL, &th_function, NULL);
sleep(5);
pthread_cancel(thread_1);
sleep(5);
}

/******************************************************/
void * th_function (void* n )
{
for (int sec =0; sec!=10;sec++)
    {
    printf ("Seconds from init thread %i\n", sec);
    sleep(1);
    }
}

The following image shows the compilation and execution of the code. As you can see, the thread is terminated with the pthread_cancel() function in the middle of the execution or 5 seconds after the start:

In this case, the thread accepts the cancellation because its attributes are set to default at creation by specifying a NULL pointer in the “attr” input arguments of the pthread_create() function.

Errors in the Use of the Pthread_Cancel() Function: What Are They and How to Identify Them

The way to determine if an error occurs when calling this function is to use an “if” condition where the input condition is a non-zero return result. The following is a code snippet using this method for error detection:

if (pthread_cancel (thread) !=0){

printf("An error occurred trying to cancel the specified thread");

}

The only error that this function can generate is the one that is defined as ISRCH in the “errno.h” header. This error is generated when a non-existent thread is referenced in the input argument of the pthread_cancel() function.

Compilation Errors in Programs with Threads

When compiling the GCC programs that use threads, the compilation may fail if it is not done correctly from the command line.

The most common error message that is issued by the compiler states that one of the thread functions that we refer to in the code is not defined.

These errors often result in wasting valuable time by checking the headers that we inserted in the code, their integrity, and the directories that are associated with the compiler since everything indicates that the problem is there.

Although the functions that cause the error are defined in the “pthread.h” header and are included in the code, the compiler does not recognize these functions unless the pthread library is called from the command line during compilation.

You can see in green the correct way to call the pthread library from the command console during compilation of programs with threads in the following:

~$ gcc -pthread path/filename.c -o out_name

As we can see in the following figure, the error disappears when the pthread library is called during compilation:

Conclusion

In this Linux Hint article, we showed you how to use the pthread_cancel() function to ask the system to terminate a running thread.

We looked at a theoretical description of this function and showed you its syntax, the input and output arguments, and the type of data that each of them accepts. After that, we implemented what we learned through a practical example with code snippets and images where we have seen how the pthread_cancel() function works in the C language.

We also added a special section where we showed you how to correctly compile the programs that contain the threads and functions from the pthread library.

About the author

Julio Cesar

Julio Cesar is a 42 years old programmer with 8 years of experience in embedded systems development, 6 years developing firmware for user interfaces in C and C++. Additionally he has 2 years of experience developing scripts for network devices and 3 years as developer of high frequency PCB (Printed Circuit Board).