| by Arround The Web | No comments

C++ std::thread Functions

A process’s single sequence stream can be termed a thread. Threads are frequently referred to as “lightweight processes” since they have some characteristics with processes. A class is to represent distinct execution threads. A single thread of execution is represented by the class thread. Multiple functions can run at once because of threads. When a thread object is created, it instantly starts to execute (subject to any OS scheduling delays) starting at the highest function specified as a function constructor. The method’s defined value is disregarded and std::terminate is invoked if it exits by raising an error.

Types of Threads

A process’s particular series stream is referred to as a thread. Threads are denoted as insubstantial procedures as they are similar to processes in many ways. Although threads are operated sequentially, they appear to be running concurrently. There are various states for each thread.

  • an electronic counter
  • a set of registers
  • a shelf area

Processes

In essence, processes are the programs that are dispatched from the ready state and scheduled for execution in the CPU. The concept of process is held by PCB (Process Control Block). A process might produce what is referred to as “Child Processes,” or new processes. The process takes longer to complete because it is isolated, which means it does not share a memory with any other processes. Any of the following states for the process could be present: new, ready, running, waiting, terminated, or suspended.

Threads

A thread is a module of a process. A process may have several threads and all of those threads are contained inside the method. Three states exist for a thread: running, ready, and blocked. The thread terminates faster than the process but it does not isolate as the process does.

The Common Characteristics between Threads and Processes Include

  • Just one thread or process can be operative at once.
  • Successive execution inside the process.
  • The ability to generate children.

The Distinctions between Processes and Thread

  • Processes are self-regulating; threads are not.
  • While processes may or may not help one another, threads are designed to do so.

Thread at User Level

It is put into practice in the user-level library; system calls are not used to construct them. Thread switching does not require an OS call or a kernel interrupt. The kernel manages them as though they were single-threaded processes since it is unaware of the user-level thread.

Benefits

  • The only attributes a thread has are a stack space, a stack pointer, and a shift register.
  • Since the kernel makes no adjustments, creation is simple.
  • Due to the absence of OS calls, thread switching is quick.
  • It is compatible with operating systems that prohibit multi-threading.

A Kernel-Level Thread

The threads are managed by the kernel. In addition, the kernel also keeps track of the processes using the conventional process table. The OS kernel has system calls for managing and creating threads.

Benefits

  • Given that the kernel has complete information about the system’s threads.
  • The scheduler may decide to give processes with a high number of threads additional time.
  • Good for regularly blocking programs.

 

Multi-Threading:

Another name for a thread is a lightweight process. By breaking a process up into several threads, parallelism is intended to be achieved. For instance, many tabs in a browser could represent various threads. Multiple threads are used by MS Word, including one for processing inputs and another for formatting the text.

Define a Thread() Function

A class thread refers to a particular thread of implementation. In C++, the term “thread class” refers to the std::thread class. Once the linked threads object has been created, the top-level method that was supplied as part of the function constructor agreement is where the thread execution begins. The implementing code that must be invoked will receive a new thread object that has been created to start a thread.

As was said earlier, std:: thread is required to start a new thread and the thread also needs to be callable. A callable is a program that must be run when the thread is active. In other words, if a new thread is required, a callable must be supplied as an argument to the constructor of an object for std:: thread. After that, the newly generated thread begins and the callable provided function is run.

Processes vs Threads

The main distinction is that whereas processes run in different memory areas, threads inside a single process shared memory space. Because threads are not completely independent of one another like processes are, they share their OS resources, code section, and data section with other threads.

Threads have Advantages over Processes

  • Responsiveness: If a process is broken up into numerous threads, each thread’s output can be returned as soon as it has finished running.
  • Quicker context switch: Context switches between threads happen more quickly than context switches within a process. The CPU has to do more overhead due to process context shifts.
  • Effective multiprocessor system use: If a process contains many threads, we can schedule those threads on different processors. As a result, it would be faster process execution.
  • Communication is facilitated by the fact that several threads share an address space. While in process, we must adhere to a particular communication method for two-process communication.
  • Resource sharing: All threads inside a process can share resources such as code, data, and files.
  • Boosted system capacity: When a task is separated into several threads, every thread operation is treated as a function, increasing the number of methods done in a given amount of time enhances the system capacity.

Thread Function in C++

In an operating system, they provide (POSIX thread) for functions, those functions related to functions. We can make a lot of threads this way to support concurrent process flow. It works best on systems with several processors or cores, where the speed of execution can be achieved by implementing threads at the kernel level. Gains can also be made in systems with a single processor by taking advantage of IO or other system services that tend to pause processes.

Create() Function

pthread_create: new thread create

Parameters

  • Thread: A pointer to an unsigned integer value that contains the thread id of the most recent thread that was started.
  • Attr: Attributes of a thread, such as its detached state, scheduling strategy, stack address, etc., are defined by a structure called attr. For default thread properties, set to NULL.
  • Start routine: A pointer to a thread’s starting subroutine. The function only has one attribute but a struct must be used if more than one value has to be supplied to the function.
  • arg: a pointer to a void that contains a pointer to the function’s parameters as provided by the preceding argument.

Exit() Function

pthread_exit: used to stop using a thread

Parameters
Reveal, a pointer to an integer that contains the thread’s return status is a required parameter for this procedure. Any thread waiting to join this thread must be able to view the return status because this variable’s scope must be global.

Join() Function

pthread_join: used to exit the thread waiting

Parameters

  • th: The thread’s waiting for thread’s identifier.
  • Thread return: A pointer to the location where the thread described in the exit status is saved.

Equal() Function

pthread_equal: determines whether or not two threads are similar. The function returns a non-zero number if the two threads are equal, else zero.

St::Thread Creation

In C++, threads are built using the std::thread class. A thread is a unique execution flow; it is similar to having a helper finish one task while you finish another one simultaneously. Once all of the thread’s code has been executed, it stops. When establishing a thread, something must be passed to be executed on it. The objects listed below can be passed to a thread.

Member Types

Id: Thread id (public)
Native_handle_type: native_handle_type (public)

The thread enables the simultaneous execution of multiple tasks. In C++, the term “thread class” refers to the std::thread class. A new thread object must be generated to start a thread and it must be supplied to the executing code that must be called. The top-level method that was supplied as part of the function constructor agreement is where the thread execution begins after the linked threads object has been created.

Callable Utilizing Object

An object could be made callable by utilizing this method. For that, a class is required and operator() must be overloaded within that class. The software that has to run when the thread is formed is included in the overloaded methods.

Callable Utilizing Pointer

A pointer will be made callable by using this method. In the thread object, the list of parameters or arguments sent to the method appears next to the function’s name.

Callable Using Function Pointer

Giving it to the thread object for execution achieves the desired result. The thread object’s function constructor receives a lambda expression named “lm” as its first argument before receiving its arguments as its second argument.

Let’s discuss different examples of std::thread functions.

Example 1

In this instance, we will utilize a thread with a pointer.

#include <iostream>
#include <thread>
class Test 
{
public:
    void execute(std::string command)
    {
        for(int i = 0; i < 8; i++)
        {
            std::cout<<command<<" :: "<<i<<std::endl;
        }
    }
};
int main()
{
    Test * testPtr = new Test();
      std::thread th(&Test::execute, testPtr, "values");
    th.join();
    delete testPtr;
    return 0;
}

First, we include the headers files <iostream> and <thread> in the program. We create the class and specify its name ‘test’. Then, we utilize the public method and execute the string command. After executing the string command, we will apply for loop and increment (0 to 8). Here, we employ the ‘cout’ statement. Next, we call the main() function. Along with this, we call the class ‘test’ and use a pointer in it. Next, the thread passes the pointer. Then, we have been using the join() function, delete the test pointer, and enter ‘return 0’.

Example 2

In this case, we will utilize a thread without a pointer.

#include <iostream>
#include <thread>
class name
{
public:
    static void test(std::string command)
    {
        for(int i = 0; i < 3; i++)
        {
            std::cout<<command<<" :: "<<i<<std::endl;
        }
    }
};
int main()
{
        std::thread th(&name::test, "name");
    th.join();
    return 0;
}

Use header files <iostream> and <thread>. Create a class and the title of the class is ‘name’. We utilize the public method and the next line uses a static member function and here we pass the string. Use the ‘for’ loop and then initialize the values from 0 to 3. The ‘cout’ statement is being used to depict the value. In the next line, we invoke the main() function, use thread, and pass the values without using a pointer. Next, we use the join() function and enter ‘return 0’.

Example 3

Here we are going to apply the void operator.

#include <iostream>
#include <thread>
using namespace std;
class lab {
public:
void operator()(int a)
{
for (int i = 0; i < a; i++)
cout << "Number of threads :" << i << "\n";
}
};
int main()
{
thread t2(lab(), 6);
t2.join();
return 0;
}

In this code, we integrate the required header files <iostream>, <thread>. We utilize standard namespace as std. We add a class named ‘lab’ and use its public method. Then, employ the void operator and initialize a variable ‘a’ in it. Here, we will employ the ‘for’ loop from 0 to the value of variable ‘a’. Further, we will print a statement “number of threads” by using the ‘cout’ statement. We invoke the main() function. Within this, a thread having the value 6 will be declared. When a thread gets a call, it executes a code and displays the message on the screen.

Conclusion

In this guide, we talked about the thread in C++ functions. Then, we observe different functions of thread in C++. We defined the thread and also its types. Also, we mentioned different parameters of the thread. We have executed numerous types of codes. In the first code, we used a thread with a pointer, it’s a non-static member function. Second, in code we use thread without pointer, it’s a static member function. Third and last code, we used the void operator and when a thread got the value it showed the message on the screen.

Share Button

Source: linuxhint.com

Leave a Reply