Callables in Multithreading

              Callables are like a function and passed to a thread. It is executed simultaneously with the thread. Let us categorize the callables as follows.

Categories:

Function:

              It creates the function to be called with thread.

C++ Program:

#include <bits/stdc++.h>

using namespace std;

void samp(int no) {

    cout <<"The number is:"<< no;

}

int main() {

    int n;

    cout<<"Enter the number "<<endl;

    cin>>n;

    thread t(samp, n);

    // Wait for thread to finish

    t.join();

    return 0;

}

Output:

Enter the number

665

The number is:665

Function Object:

The callable object  is pass to the constructor which initializing a thread.

C++ Program:

#include <iostream>

#include <thread>

using namespace std;

// Define a class SumFunc

class SumFunc {

public:

    int no;

    SumFunc(int a) : no(a) {}

    // The operator() is overloaded

    void operator()() const {

        cout <<"The number given is:"<< no;

    }

};

int main() {

    // A thread object is created with function call

    thread t(SumFunc(10));

    t.join();

    return 0;

}

Output:

The number given is:10

Lambda Expression:

It uses the lambda expression as callables. This callable passed directly inside the thread object.

C++ Program:

#include <iostream>

#include <thread>

using namespace std;

int main() {

    int no;

    cout<<"Enter the number:"<<endl;

    cin>>no;

    // Create a thread that runs

    // a lambda expression

    thread t([](int no){

        cout <<"The number is:"<<no;

    }, no);

    // Wait for the thread to complete

    t.join();

    return 0;

}

Output:

Enter the number:

78

The number is:

78

Non- static or static Member Function:

When you the thread for static and non static member function, here, is the solution.

C++ Program:

#include <iostream>

#include <thread>

using namespace std;

class SampleClass {

public:

    // let us create two Non-static member functions

    void first_fun(int n) {

        cout <<"The first number is:"<<n << endl;

    }

    // Second function

    static void second_fun(int n) {

        cout <<"The second number is:"<< n;

    }

};

int main() {

    SampleClass obj;

    // Passing object and parameter

    thread t1(&SampleClass::first_fun, &obj, 5);

        t1.join();

    thread t2(&SampleClass::second_fun, 7);

     t2.join(); 

    return 0;

}

Output:

The first number is:5

The second number is:7

These are the four categories of callable in thread management. Hope, you understood the concepts. Keep Coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.