Thread functions in C/C++ - GeeksforGeeks (2024)

Last Updated : 09 May, 2023

Improve

In a Unix/Linux operating system, the C/C++ languages provide the POSIX thread(pthread) standard API(Application program Interface) for all thread related functions. It allows us to create multiple threads for concurrent process flow. It is most effective on multiprocessor or multi-core systems where threads can be implemented on a kernel-level for achieving the speed of execution. Gains can also be found in uni-processor systems by exploiting the latency in IO or other system functions that may halt a process.

We must include the pthread.h header file at the beginning of the script to use all the functions of the pthreads library. To execute the c file, we have to use the -pthread or -lpthread in the command line while compiling the file.

cc -pthread file.c orcc -lpthread file.c

The functions defined in the pthreads library include:

  1. pthread_create: used to create a new thread

    Syntax:

    int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg);

    Parameters:

    • thread: pointer to an unsigned integer value that returns the thread id of the thread created.
    • attr: pointer to a structure that is used to define thread attributes like detached state, scheduling policy, stack address, etc. Set to NULL for default thread attributes.
    • start_routine: pointer to a subroutine that is executed by the thread. The return type and parameter type of the subroutine must be of type void *. The function has a single attribute but if multiple values need to be passed to the function, a struct must be used.
    • arg: pointer to void that contains the arguments to the function defined in the earlier argument
  2. pthread_exit: used to terminate a thread

    Syntax:

    void pthread_exit(void *retval);

    Parameters: This method accepts a mandatory parameter retval which is the pointer to an integer that stores the return status of the thread terminated. The scope of this variable must be global so that any thread waiting to join this thread may read the return status.

  3. pthread_join: used to wait for the termination of a thread.

    Syntax:

    int pthread_join(pthread_t th, void **thread_return);

    Parameter: This method accepts following parameters:

    • th: thread id of the thread for which the current thread waits.
    • thread_return: pointer to the location where the exit status of the thread mentioned in th is stored.
  4. pthread_self: used to get the thread id of the current thread.

    Syntax:

    pthread_t pthread_self(void);
  5. pthread_equal: compares whether two threads are the same or not. If the two threads are equal, the function returns a non-zero value otherwise zero.

    Syntax:

    int pthread_equal(pthread_t t1, pthread_t t2);

    Parameters: This method accepts following parameters:

    • t1: the thread id of the first thread
    • t2: the thread id of the second thread
  6. pthread_cancel: used to send a cancellation request to a thread

    Syntax:

    int pthread_cancel(pthread_t thread);

    Parameter: This method accepts a mandatory parameter thread which is the thread id of the thread to which cancel request is sent.

  7. pthread_detach: used to detach a thread. A detached thread does not require a thread to join on terminating. The resources of the thread are automatically released after terminating if the thread is detached.

    Syntax:

    int pthread_detach(pthread_t thread);

    Parameter: This method accepts a mandatory parameter thread which is the thread id of the thread that must be detached.

Example: A simple implementation of threads may be as follows:

// C program to show thread functions

#include <pthread.h>

#include <stdio.h>

#include <stdlib.h>

void* func(void* arg)

{

// detach the current thread

// from the calling thread

pthread_detach(pthread_self());

printf("Inside the thread\n");

// exit the current thread

pthread_exit(NULL);

}

void fun()

{

pthread_t ptid;

// Creating a new thread

pthread_create(&ptid, NULL, &func, NULL);

printf("This line may be printed"

" before thread terminates\n");

// The following line terminates

// the thread manually

// pthread_cancel(ptid);

// Compare the two threads created

if(pthread_equal(ptid, pthread_self()))

printf("Threads are equal\n");

else

printf("Threads are not equal\n");

// Waiting for the created thread to terminate

pthread_join(ptid, NULL);

printf("This line will be printed"

" after thread ends\n");

pthread_exit(NULL);

}

// Driver code

int main()

{

fun();

return 0;

}

Output:

This line may be printed before thread terminatesThreads are not equalInside the threadThis line will be printed after thread ends

Explanation: Here two threads of execution are created in the code. The order of the lines of output of the two threads may be interchanged depending upon the thread processed earlier. The main thread waits on the newly created thread for exiting. Therefore, the final line of the output is printed only after the new thread exits. The threads can terminate independently of each other by not using the pthread_join function. If we want to terminate the new thread manually, we may use pthread_cancel to do it.

Note: If we use exit() instead of pthread_exit() to end a thread, the whole process with all associated threads will be terminated even if some of the threads may still be running.



Like Article

Suggest improvement

Next

Function Call Stack in C

Share your thoughts in the comments

Please Login to comment...

Thread functions in C/C++ - GeeksforGeeks (2024)

FAQs

Thread functions in C/C++ - GeeksforGeeks? ›

In C++, class thread denotes a single thread of execution. It permits the execution of several functions at the same time. The class that denotes the thread class in C++ is std::thread. To start a thread, you need to create a new thread object and pass it to the code that will be executed.

What is the thread function in C++? ›

In C++, class thread denotes a single thread of execution. It permits the execution of several functions at the same time. The class that denotes the thread class in C++ is std::thread. To start a thread, you need to create a new thread object and pass it to the code that will be executed.

Can you do threading in C++? ›

Multithreading support was introduced in C++11. Prior to C++11, we had to use POSIX threads or <pthreads> library. While this library did the job the lack of any standard language-provided feature set caused serious portability issues. C++ 11 did away with all that and gave us std::thread.

How to create a thread function in C? ›

In main(), we declare a variable called thread_id, which is of type pthread_t, which is an integer used to identify the thread in the system. After declaring thread_id, we call pthread_create() function to create a thread. pthread_create() takes 4 arguments.

How to run two threads simultaneously in C++? ›

Multithreading in C++ can be achieved using the thread library from the C++ Standard Library or by using platform-specific APIs, such as the Windows API or POSIX threads. To create a new thread in C++, you can use the std::thread class from the <thread> library.

How many threads should I use in C++? ›

The optimal number of threads that computer will suggest would be a number such as 4, 8, 12, or 16 (depending on whether there is a hardware support for multi-threading). The programmers should try to use the optimal number of threads, but they are not required to.

How do you identify a thread in C++? ›

To identify a thread, we must do the following: 1) Get and save its id. 2) Within a function running in the thread, get the thread's id again and compare it with the saved id. (The program is from Josuttis' book "The C++ Standard Library", 2nd Ed.)

What are the ways to create a thread in C++? ›

In this program, we first define a function myFunction that will be executed by the new thread. We then create a new thread newThread and pass the function pointer to its constructor. The join method is called on newThread to wait for the new thread to finish execution before the main thread continues.

How to synchronize threads in C++? ›

In C++, thread synchronization is possible using the following methods:
  1. Mutex in C++ Mutex is a synchronization primitive that locks the access to the shared resource if some thread is already accessing it. ...
  2. Mutex in C++
Jan 1, 2024

Is there threading in C? ›

C does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C program using POSIX.

How to run a thread in C? ›

We must include the pthread. h header file at the beginning of the script to use all the functions of the pthreads library. To execute the c file, we have to use the -pthread or -lpthread in the command line while compiling the file.

Which language is best for multithreading? ›

Java is a widely-used multi-threaded programming language known for its robust support for concurrency through the Java Thread API. Developers can create and manage threads to execute tasks concurrently, making Java suitable for various applications, such as web servers, data processing, and scientific computing.

How does thread join work in C? ›

Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.

Is C++ single-threaded? ›

C++ is definitely not single threaded and has full support for multiple threads, thread-local variables, thread synchronization functions, etc. Javascript is single threaded because you cannot have 2 sets of consecutive lines of code running interleaved or simultaneously on multiple cores.

How to use mutex in C++? ›

The use of mutex can be divided into three steps:
  1. Create a std::mutex Object. std::mutex mutex_object_name;
  2. Lock the Thread. The lock() function of the std::mutex class locks the thread and allows only the current thread to run until it is unlocked. ...
  3. Unlock the thread.
Nov 20, 2023

How to wait for threads to finish in C++? ›

Use pthread_join(3THR) to wait for a thread to terminate. Prototype: int pthread_join(thread_t tid , void ** status ); #include <pthread.

What is the use of thread function? ›

Thread functions in C/C++
  1. pthread_create: used to create a new thread. ...
  2. pthread_exit: used to terminate a thread. ...
  3. pthread_join: used to wait for the termination of a thread. ...
  4. pthread_self: used to get the thread id of the current thread. ...
  5. pthread_equal: compares whether two threads are the same or not.
May 9, 2023

What is thread and its function? ›

A thread also exists as the processing focus of a software program, such as an operating system (OS) or application. In technology, a thread is typically the smallest set or sequence of instructions that a computer can manage and execute; it is the basic unit of processor (CPU) utilization.

What is the basic function of a thread? ›

The basic function of a thread is to deliver aesthetics and performance in stitches and seams.

What is the main thread function? ›

When an application component starts and the application doesn't have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread, called the main thread.

Top Articles
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated:

Views: 6741

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.