what are different ways to create threads in c++11? There are four ways to create threads in c++11 programming language.

  1. Create thread with a function pointer
  2. Create thread with a function object or functor
  3. Create a thread with a lambda function
  4. Create a thread with a class member function

C++11 thread creation with a function pointer?

#include <iostream>
#include <thread>

void foo() {
  std::cout << "hello thread \n";
}

int main() {
    // main process or thread
    // create thread for foo to run
    std::thread t(foo);
    t.join();
    return 0;
}

How to create a thread using Function Objects or functors

The below example creates a functor object which adds two numbers. The program is creating a thread by passing a functor in thread object t.

#include <iostream>
#include <thread>

class Add{
public:
    void operator()(int a, int b)
    {
      int c = a + b;
      std::cout << c << std::endl;
    }
};

int main() {
    // main process or thread
    // create thread for foo to run
    std::thread t((Add()),4,5);
    t.join();
    return 0;
}

How to create a thread using lamda expression in c++11

To know what is lamda expression read the link http://wikistack.com/lambda-expression-in-c11-and-c14/

#include <iostream>
#include <thread>

int main() {
    std::thread t(
    [] { std::cout << "hello \n";  }
    );

    t.join();
    return 0;
}
// g++ -std=c++11 sample.cpp -pthread -osample

Create a thread with a class member function

#include <iostream>
#include <thread>

class foo
{
  public:
     void hello() {
          std::cout << "hello thread\n";
     }
};


int main() {
    foo obj;
    std::thread t(&foo::hello,&obj);
    t.join();
    return 0;
}

 



Related Contents to follow